python - 在列表理解中解包列表

标签 python list 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)]

我得到以下结果 [['一', '二'], ['三']] 但我想要的是 ['一', '二', '三']

如何在列表理解中解压这些列表?

最佳答案

您可以使用嵌套理解:

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

顺序一直让我感到困惑,但本质上它的嵌套方式与循环相同。例如最左边的可迭代对象是最外层循环,最右边的可迭代对象是最内层循环。

关于python - 在列表理解中解包列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25558999/

相关文章:

python - 使用带有LinkedBrush的matplotlib mpld3的Json序列化错误

c - 删除单向链表中所有出现的元素

python - 如何将属性添加到字典列表到Python中的列表理解?

python - 在同一事件循环中运行 Qt 和 Websockets 服务器

python - 正确模拟在另一个 celery 任务中调用的 celery 任务

python : Get value from a list of Json dictionary

c# - 根据 List<string> 检查文本文件的内容

python - 如何使用列表推导式比较和删除嵌套列表的第二个元素?

python - 列表理解与迭代

python:读取文件并将其拆分为字典列表