列表理解的循环顺序不同



考虑以下内容:

xtest=np.arange(0,10)
ytest=np.arange(0,3)
zValuesBisBis=[[j for j in xtest] for i in ytest]
zValuesBisBisBis=[j for j in xtest for i in ytest]
print(zValuesBisBis)
print(zValuesBisBisBis)

它分别返回给我:

[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9]

我不明白为什么循环顺序在两者之间发生变化。我的意思是,列表的内容显然不一样(一个是列表,另一个是数字列表(。但是循环的顺序应该是相同的,即我期望第二个打印是"循环";扁平的";第一个版本。

为什么会有这样的行为?

如果我们取消理解,我们会得到以下内容。

# arr = [[j for j in xtest] for i in ytest]
arr = []
for i in ytest:
t = []
for j in xtest:
t.append(j)
arr.append(t)
# arr = [j for j in xtest for i in ytest]
arr = []
for j in xtest:
for i in ytest:
arr.append(j)

正如你所看到的,第二个实际上是以直接的方式嵌套循环,而不是你所期望的相反的方式。

[[j for j in xtest] for i in ytest]强制内部循环(强制j循环为内部循环(。[j for j in xtest for i in ytest]将内部循环保留为隐含循环,最终成为最右边的循环,即i循环。

有关如何评估多个循环的示例,请参阅文档。

最新更新