列表理解中的双重迭代 [英] Double Iteration in List Comprehension
问题描述
在Python中,列表推导中可以有多个迭代器,例如
In Python you can have multiple iterators in a list comprehension, like
[(x,y) for x in a for y in b]
对于一些合适的序列a和b.我知道Python列表推导的嵌套循环语义.
for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.
我的问题是:理解中的一个迭代器可以引用另一个吗?换句话说:我能有这样的东西吗?
My question is: Can one iterator in the comprehension refer to the other? In other words: Could I have something like this:
[x for x in a for a in b]
外部循环的当前值是内部循环的迭代器吗?
where the current value of the outer loop is the iterator of the inner?
例如,如果我有一个嵌套列表:
As an example, if I have a nested list:
a=[[1,2],[3,4]]
列表理解表达式将如何获得此结果:
what would the list comprehension expression be to achieve this result:
[1,2,3,4]
?? (请只列出理解答案,因为这是我要查找的内容.)
?? (Please only list comprehension answers, since this is what I want to find out).
推荐答案
Gee,我想我找到了答案:我对哪个循环是内部循环和哪个循环是外部循环不够注意.列表理解应为:
Gee, I guess I found the anwser: I was not taking care enough about which loop is inner and which is outer. The list comprehension should be like:
[x for b in a for x in b]
以获得所需的结果,是的,一个当前值可以作为下一个循环的迭代器.
to get the desired result, and yes, one current value can be the iterator for the next loop.
这篇关于列表理解中的双重迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!