2014-08-28 33 views
3
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)] 

我得到以下結果[「一」,「二」],[「三」] ,但我要的是[「一」,「二」,「三']解壓名單列表綜合

如何在列表理解中解開這些列表?

回答

5

您可以使用嵌套的理解:

>>> [x for a in arg if dictAll.has_key(a) for x in dictAll[a]] 
['one', 'two', 'three'] 

訂單一直困惑我,但它本質上築巢它將如果它是一個循環的方式相同。例如最左邊的迭代是最外面的循環,最右邊的迭代是最內部的循環。

+0

+1實際解釋爲什麼OP的代碼沒有得到所需的結果 – 2014-08-28 22:39:26

+0

非常感謝!那回答了! – user3835779 2014-08-28 22:56:46

5

您可以使用itertools.chain.from_iterable

>>> from itertools import chain 
>>> list(chain.from_iterable(dictAll.get(a, []) for a in arg)) 
['one', 'two', 'three'] 

也不要使用dict.has_key它已被棄用(和Python 3中刪除),你可以簡單地檢查使用key in dict的關鍵。

+0

非常感謝!那也回答了! – user3835779 2014-08-28 22:57:16