You are talking about list comprehensions, not generator expressions.
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:
When a list comprehension is supplied, it consists of a single expression followed by at least one for
clause and zero or more for
or if
clauses. In this case, the elements of the new list are those that would be produced by considering each of the for
or if
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]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…