gpt4 book ai didi

python-2.7 - 列表理解中的Python奇怪行为

转载 作者:行者123 更新时间:2023-12-01 01:02:58 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





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正如传入的那样。

领悟设置为1 , 2 ,然后最后 3 .

相反,将其更改为

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

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

Python 3

这已被修复。

From the BDFL himself :

We also made another change in Python 3, to improve equivalence between list comprehensions and generator expressions. In Python 2, the list comprehension "leaks" the loop control variable into the surrounding scope:


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

This was an artifact of the original implementation of list comprehensions; it was one of Python's "dirty little secrets" for years. It started out as an intentional compromise to make list comprehensions blindingly fast, and while it was not a common pitfall for beginners, it definitely stung people occasionally. For generator expressions we could not do this. Generator expressions are implemented using generators, whose execution requires a separate execution frame...

However, in Python 3, we decided to fix the "dirty little secret" of list comprehensions by using the same implementation strategy as for generator expressions. Thus, in Python 3, the above example (after modification to use print(x) :-) will print 'before'.

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com