嵌套列表理解 [英] nested list comprehensions
问题描述
我尝试在内部列表中使用外部列表理解的值:
I tried to use the value of an outer list comprehension in an inner one:
[ x for x in range(y) for y in range(3) ]
但是不幸的是,这会引发NameError,因为名称y
是未知的(尽管外部列表理解指定了它).
But unfortunately this raises a NameError because the name y
is unknown (although the outer list comprehension specifies it).
这是Python的限制(尝试过2.7.3和3.2.3)还是有充分的理由解释为什么它不起作用?
Is this a limitation of Python (2.7.3 and 3.2.3 tried) or is there a good reason why this cannot work?
有计划摆脱限制吗?
是否有变通方法(某些不同的语法,也许我没有弄清楚)来实现我想要的?
Are there workarounds (some different syntax maybe I didn't figure out) to achieve what I want?
推荐答案
您正在谈论的是列表理解,而不是生成器表达式.
You are talking about list comprehensions, not generator expressions.
您需要交换for循环:
You need to swap your for loops:
[ x for y in range(3) for x in range(y) ]
您需要阅读它们,就像它们嵌套在常规循环中一样:
You need to read these as if they were nested in a regular loop:
for y in range(3):
for x in range(y):
x
具有多个循环的列表推导遵循相同的顺序.请参阅列表理解文档:
List comprehensions with multiple loops follow the same ordering. See the list comprehension documentation:
提供列表理解后,它由一个表达式组成,后接至少一个
for
子句和零个或多个for
或if
子句.在这种情况下,新列表的元素是通过将每个for
或if
子句视为一个块,从左向右嵌套,并在每次到达最里面的块.
When a list comprehension is supplied, it consists of a single expression followed by at least one
for
clause and zero or morefor
orif
clauses. In this case, the elements of the new list are those that would be produced by considering each of thefor
orif
clauses a block, nesting from left to right, and evaluating the expression to produce a list element each time the innermost block is reached.
生成器表达式当然也是一样,但是它们使用()
括号而不是方括号,并且不会立即实现:
The same thing goes for generator expressions, of course, but these use ()
parenthesis instead of square brackets and are not immediately materialized:
>>> (x for y in range(3) for x in range(y))
<generator object <genexpr> at 0x100b50410>
>>> [x for y in range(3) for x in range(y)]
[0, 0, 1]
这篇关于嵌套列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!