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/