[英]Python 3 2-D list initialization breaks in Python 2
I'm trying to initialize a 2-D list using list comprehensions, but I'm seeing different results in Python 2 vs. Python 3 and I have no idea why.我正在尝试使用列表推导来初始化一个二维列表,但是我在 Python 2 和 Python 3 中看到了不同的结果,我不知道为什么。 Sample code (the import
is just so I can use v3 print statements in v2):示例代码( import
只是为了让我可以在 v2 中使用 v3 打印语句):
from __future__ import print_function
ROW = 3
COL = 3
myList = [0 for i in range(ROW)]
#print('myList1 =', myList, 'len =', len(myList))
for i in range(len(myList)):
#print('i =', i)
myList[i] = [-1 for i in range(COL)]
#myList[0] = [-1 for i in range(COL)]
print('myList2 =', myList)
Python 3 output: myList2 = [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
Python 3 输出: myList2 = [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
Python 2 output: myList2 = [0, 0, [-1, -1, -1]]
Python 2 输出: myList2 = [0, 0, [-1, -1, -1]]
The Python 3 behavior is what I would expect, and the commented out print statements are what I used to confirm that everything between the two up until the myList[i]
assignment is the same. Python 3 的行为是我所期望的,注释掉的打印语句是我用来确认两者之间的所有内容直到myList[i]
分配是相同的。 If I manually do, eg, myList[0] =...
outside of the for loop it updates that element as expected.如果我手动执行,例如myList[0] =...
在 for 循环之外,它会按预期更新该元素。 What am I missing here?我在这里想念什么?
You are using i
twice within the same for loop, once in the list-comprehension and once as a run variable for the outer for-loop.您在同一个 for 循环中使用i
两次,一次在列表理解中,一次作为外部 for 循环的运行变量。 As detailed in this post , variables used in a list comprehension "leak" into the surrounding scope in python 2x.如本文所述,列表推导中使用的变量“泄漏”到 python 2x 中的周围范围。 So your for loop processes like this:所以你的 for 循环过程是这样的:
i=0
, from the for loop:从 for 循环中设置i=0
: List comprehension generates list of -1
's and sets i=2
列表理解生成-1
的列表并设置i=2
myList[i] =
is actually myList[2] =
myList[i] =
实际上是myList[2] =
i=1
, from the for loop:从 for 循环中设置i=1
: List comprehension generates list of -1
's and sets i=2
列表理解生成-1
的列表并设置i=2
myList[i] =
is actually myList[2] =
myList[i] =
实际上是myList[2] =
i=2
, from the for loop:从 for 循环中设置i=2
: List comprehension generates list of -1
's and sets i=2
列表理解生成-1
的列表并设置i=2
myList[i] =
is actually myList[2] =
myList[i] =
实际上是myList[2] =
Which generates the list [0, 0, [-1, -1, -1]]
, because we only ever changed myList[2]
这会生成列表[0, 0, [-1, -1, -1]]
,因为我们只更改了myList[2]
The simplest fix is to use different variables, ie j in one place:最简单的解决方法是使用不同的变量,即 j 在一个地方:
from __future__ import print_function
ROW = 3
COL = 3
myList = [0 for i in range(ROW)]
for i in range(len(myList)):
#Use j for the list comprehension
myList[j] = [-1 for j in range(COL)]
print('myList2 =', myList)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.