I’m stuck on task 8, where it asks me to clean up the strings within a list which is, itself, within another list.
My code:
transactions_clean = []
for i in daily_transactions_split:
for e in i:
transactions_clean.append(e.strip())
The above creates a new list with all the strings stripped of white space. But it gets rid of the original lists within the list. I would like to keep the original structure intact, but with cleaned internal list.
Must’ve spent 2 hours trying to figure this out. So help would be very much appreciated.
So, consider what is happening. You take each element of a list which is also a list, then you iterate though the elements of that list, strip the white space, and append them to the new list.
What you are wanting to do is strip the white space from each element inside the nested list, and then append the entire list to the new list, so that you end up with a list of lists like you originally had.
Do you see the difference in what I wrote? The second part includes some extra steps. Consider how you could make changes to each element of the nested list, and then append the list.
It took a few mins to figure out what mtf said, but it basically means below:
My original codes: #8
transactions_clean = []
for transaction in daily_transactions_split:
for data in transaction:
data_clean = data.strip()
transactions_clean.append(data_clean)
It turns out adding all transaction data in one single list, instead to returning the original nested list structure.
The solution is following: #8
transactions_clean = []
for transaction in daily_transactions_split:
for i in range(len(transaction)):
transaction[i] = transaction[i].strip()
transactions_clean.append(transaction)
The keys are:
1/ Strip and replace the transaction data directly by
“transaction[i] = transaction[i].strip()” in the second for loop
2/ Append the whole transaction (instead of each transaction data) into the “transaction_clean” list. This is done by appending under first for loop instead of second for loop