簡體   English   中英

在列表理解中解壓縮列表

[英]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)]

我得到以下結果[['one','two'],['three']]但我想要的是['one','two','three']

如何在列表解析中解壓縮這些列表?

您可以使用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使用key in dict檢查key in dict

您可以使用嵌套理解:

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

這個命令一直讓我感到困惑,但基本上它就像它是一個循環一樣。 例如,最左邊的可迭代是最外面的循環,最右邊的可迭代是最里面的循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM