开发者

Can someone explain this program to me?

开发者 https://www.devze.com 2023-02-21 21:28 出处:网络
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)]

What does the following expression produce as a value:

[(x, x*y) for x in range(2) for y in range(2)]
  1. [(0,0), (0,1), (1,0), (1,1)]

  2. [0, 1, 2]

  3. [(0,开发者_如何学运维0), (1,0), (0,0), (1,1)]

  4. [(0,0), (0,0), (1,0), (1,1)]

  5. 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)
0

精彩评论

暂无评论...
验证码 换一张
取 消