listA = ["one", "two"]
listB = ["three"]
listC = ["four", "five", "six"]
listAll = listA + listB + listC
dictAll = {'all':listAll, 'A':listA, 'B':listB, 'C':listC,}
arg = ['foo', 'A', 'bar', 'B']
result = [dictAll[a] for a in arg if dictAll.has_key (a)]
I get the following result [['one', 'two'], ['three']] but what I want is ['one', 'two', 'three']
how do I unpack those lists in the list comprehension?
You can use a nested comprehension:
>>> [x for a in arg if dictAll.has_key(a) for x in dictAll[a]]
['one', 'two', 'three']
The order has always been confusing to me, but essentially it nests the same way it would if it were a loop. e.g. the left most iterable is the outermost loop and the right most iterable is the innermost loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With