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']]
但我想要的是['一','二','三']
如何在列表理解中解开这些列表?

最佳答案

您可以使用嵌套理解:

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

这个顺序一直让我困惑,但本质上它的嵌套方式与它是一个循环时的嵌套方式相同。最左边的iterable是最外面的循环,最右边的iterable是最里面的循环。

10-08 04:07