Assume
thread_sold = ['white', 'white&blue', 'white&blue', 'white', 'white&yellow', 'purple', 'purple&yellow', 'purple&yellow']
I need all items from that list, sometimes separated by & sometimes not. The below function works, but I'd like to know how to do this with list comprehension.
def cant_list_comprehend(lst):
thread_sold_split = []
for i in lst:
if "&" in i:
for x in i.split("&"):
thread_sold_split.append(x)
else:
thread_sold_split.append(i)
return thread_sold_split
returns ['white', 'white', 'blue', 'white', 'blue', 'white', 'white', 'yellow', 'purple', 'purple', 'yellow', 'purple', 'yellow', 'blue', 'blue', 'purple', 'blue', 'white', 'white'...]
list comprehension I tried:
thread_sold_split_bad = [
[x for x in y.split("&")] if "&" in y else y for y in thread_sold
]
returns ['white', ['white', 'blue'], ['white', 'blue'], 'white', ['white', 'yellow'], 'purple', ['purple', 'yellow'],...]
I'd like to avoid adding named functions to my code if it can be avoided, I'm also interested in solving this with lambda functions, although I'm learning basic stuff at the moment.
CodePudding user response:
thread_sold_split_bad = [
[x for x in y.split("&")] if "&" in y else y for y in thread_sold
]
Your attempt above does not work because you are doing nested list comprehensions instead of a plain comprehension (notice the brackets inside the main brackets). Here is the corrected version:
>>> thread_sold_split = [x for y in thread_sold for x in y.split("&")]
>>> print(thread_sold_split)
['white', 'white', 'blue', 'white', 'blue', 'white', 'white', 'yellow', 'purple', 'purple', 'yellow', 'purple', 'yellow']
CodePudding user response:
You could use functools.reduce
:
from functools import reduce
reduce(lambda x, y: x y, [x.split("&") for x in thread_sold])
or
import itertools
list(itertools.chain.from_iterable(x.split("&") for x in thread_sold))
OUTPUT
['white', 'white', 'blue', 'white', 'blue', 'white', 'white', 'yellow', 'purple', 'purple', 'yellow', 'purple', 'yellow']