简体   繁体   中英

Can someone explain this program to me?

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.

read as:

for x in range(2): # 0,1
  for y in range(2): # 0,1
     (x, x*y)

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 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM