Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack List in List Comprehension

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?

like image 582
user3835779 Avatar asked Dec 08 '22 06:12

user3835779


1 Answers

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.

like image 118
mgilson Avatar answered Dec 11 '22 09:12

mgilson