link: [https://www.codecademy.com/courses/learn-python-3/projects/thread-shed]
When trying different things to solve Ex. 18, I stumbled upon sth I cannot yet understand.
To begin with, this is my output for print(thread_sold):
['white', 'white&blue', 'white&blue', 'white', 'white&yellow', 'purple', 'purple&yellow', 'purple&yellow', 'blue', 'blue', 'purple&blue', 'white', 'white&red', 'white&blue&red', 'blue', 'green&blue', 'green&blue&red', ...]
The task is:" iterate through thread_sold. For single colors, append that color to thread_sold_split
. If it is multiple colors, first split the string around the &
character and then add each color indivudally to thread_sold_split
.
My code:
print(thread_sold)
thread_sold_split=[]
for i in thread_sold:
if "&" not in i:
thread_sold_split.append(i)
else:
Now the tricky part. For testing, I try the line:
thread_sold_split.append(i.split("&")[0])
which gives me this:
['white', 'white', 'white', 'white', 'white', 'purple', 'purple', 'purple', 'blue', 'blue', 'purple', 'white', 'white', 'white', 'blue', 'green' ...]
Which is correct.
But when attempting to add list comprehension like this:
thread_sold_split.append(i.split("&")[t] for t in range(len(i)))
I get this as a result:
['white', <generator object <genexpr> at 0x7f0db0a8d570>, <generator object <genexpr> at 0x7f0db0a8d5c8>, 'white', <generator object <genexpr> at ...]
Which isn’t wrong, I think, it just gives the location of the string element instead of its label. I don’t know how to change that though… Any help or should I try a different approach?