我确信已经有很多关于列表理解的问题被问到了,但是我有一个关于一个非常特殊的案例,涉及到嵌套循环和联合引用,我在其他地方找不到答案。
假设你有一个满足两个约束的字典:(1)字典中的每一个值都是任意长度的列表,(2)字典之外存在一些元素,这些元素是字典中键的子集(这是超出这个问题范围的原因所必需的)。
?看起来有点像这样:

someDict = {'a':[0, 1], 'b':[2, 3], 'c':[4, 5], 'd':[6, 7], 'e':[8, 9]}
supraList = ['b', 'c', 'd']

Now what I want to do is:
(1)只循环浏览某个dict的列表,该列表的键也是前列表的元素;
2)将这些someDict列表的元素(而不是列表本身)添加到一些新的超级列表中。
The effect is something like this:
... CODE ...
newSupraList = [2, 3, 4, 5, 6, 7]


通过循环实现这一点有点像:
newSupraList = []
for i in supraList:
    for j in someDict[i]:
        newSupraList.append(j)

?我能写的最好的理解(而且很难看)是:
newSupraList = [[2, 3], [4, 5], [6, 7]]

。循环可能更好的可读性,但我认为它在任何情况下都很有趣!

最佳答案


>>> [x for y in supraList for x in someDict[y]]
[2, 3, 4, 5, 6, 7]

或者,您可以使用forfromchain
打开包装:
>>> from itertools import chain
>>> list(chain(*(someDict[x] for x in supraList)))
[2, 3, 4, 5, 6, 7]

With itertools:
>>> list(chain.from_iterable(someDict[x] for x in supraList))
[2, 3, 4, 5, 6, 7]

关于python - 列表理解与某种循环相互依赖?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35566807/

10-15 08:54