This question already has answers here:
List comprehension rebinds names even after scope of comprehension. Is this right?

(6 个回答)


7年前关闭。



def nrooks(n):
    #make board
    print n # prints 4
    arr = [0 for n in range(n)] # if 0 for n becomes 0 for x, it works fine
    print n # prints 3 instead of 4

nrooks(4)

为什么第二个 n 变成了 3 ,与给定的参数不同?

最佳答案

Python 2

列表推导式中使用的 n 变量与传入的 n 变量相同。

理解将其设置为 12 ,最后是 3

相反,将其更改为

arr = [0 for _ in range(n)]

或(令人惊讶!)
arr = list(0 for n in range(n))

Python 3

这已被修复。

From the BDFL himself :


x = 'before'
a = [x for x in 1, 2, 3]
print x # this prints '3', not 'before'

关于python-2.7 - 列表理解中的Python奇怪行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20510190/

10-11 19:00