>>> c = 'A/B,C/D,E/F'
>>> [a for b in c.split(',') for (a,_) in b.split('/')]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
ValueError: need more than 1 value to unpack
The expected result is ['A', 'C', 'E'].
This is how I’d expect to do it, but apparently it’s back to front in Python:
>>> [a for (a, _) in b.split('/') for b in c.split(',')]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
The reason you are failing is
b.split('/')is not yielding a 2-tuple. A double list comprehension implies you want to treat the cartesian product as a flat stream and not a matrix. That is:You are not looking for 6 answers, you are looking for 3. What you want is:
Even if you used a nested list comprehension, you would get you the cartesian product (3×2=6) and realize that you have duplicate information (you don’t need the x2):
The following are equivalent ways to do things. I sort of gloss over the major difference between generators and lists in this comparison though.
Cartesian product in list form:
Cartesian product in matrix form:
Repeated application of function to list