Unzip a list in a list
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 I want this ['one', 'two', 'three']
how do i unpack these lists in a list comprehension?
+3
source to share
2 answers
You can use nested understanding:
>>> [x for a in arg if dictAll.has_key(a) for x in dictAll[a]]
['one', 'two', 'three']
The order has always baffled me, but in essence it nests just as if it were a cycle. for example, the left most repetitive is the outermost cycle, and the rightmost fighter is the innermost cycle.
+5
source to share
You can use itertools.chain.from_iterable
:
>>> from itertools import chain
>>> list(chain.from_iterable(dictAll.get(a, []) for a in arg))
['one', 'two', 'three']
Also don't use dict.has_key
, it is deprecated (and removed in Python 3), you can just check the key using key in dict
.
+5
source to share