What does the following expression produce as a value:
[(x, x*y) for x in range(2) for y in range(2)]
[(0,0), (0,1), (1,0), (1,1)]
[0, 1, 2]
[(0,开发者_如何学运维0), (1,0), (0,0), (1,1)]
[(0,0), (0,0), (1,0), (1,1)]
None of the above
The answer is 4, but I don't understand why.
Assuming python 2.
range(2)
returns the list [0, 1]
[(x, x*y) for x in [0, 1] for y in [0,1]]
Thus x and y will be all combinations of the lists [0, 1]
and [0, 1]
[(x, x*y) for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]]
x y x*y (x, x*y)
0 0 0 (0, 0)
0 1 0 (0, 0)
1 0 0 (1, 0)
1 1 1 (1, 1)
read as:
for x in range(2): # 0,1
for y in range(2): # 0,1
(x, x*y)
Read this as
list = [];
for x in range(2):
for y in range(2):
list.append((x, x*y))
Basically it will iterate 4 times with the following X,Y values
X=0, Y=0
X=0, Y=1
X=1, Y=0
X=1, Y=1
Zero times anything will always be zero, so you get your 4 arrays
First Index = 0, 0*0
Second Index = 0, 0*1
Third Index = 1, 1*0
Fourth Index = 1, 1*1
Nested list comprehensions work in the same way as if you had written for loops like that.
So your example list comprehension works like this generator function:
def example():
for x in range(2):
for y in range(2):
yield (x, x*y)
精彩评论