简体   繁体   English

有人可以向我解释这个程序吗?

[英]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. 答案是4 ,但我不明白为什么。

read as: 读为:

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

Assuming python 2. 假设python 2。

range(2) returns the list [0, 1] range(2)返回列表[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和y将是列表[0, 1][0, 1] [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,Y值迭代4次

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 零乘以零将始终为零,因此得到4个数组

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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