繁体   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