gpt4 book ai didi

python - python2 中的理解列表工作正常,但我在 python3 中遇到错误

转载 作者:太空宇宙 更新时间:2023-11-03 11:15:23 25 4
gpt4 key购买 nike

我有以下使用综合列表的代码:

x = int ( input())  
y = int ( input())
z = int ( input())
n = int ( input())


ret_list = [ (x,y,z) for x in range(x+1) for y in range(y+1) for z in
range(z+1) if x+y+z!=n ]
print(ret_list)

在 python2 中按预期工作。但是在 python3 中我得到以下错误:

print([ (x,y,z) for x in range(x+1) for y in range(y+1) for z in range(z+1) if 
x+y+z!=n ])
File "tester.py", line 16, in <listcomp>
print([ (x,y,z) for x in range(x+1) for y in range(y+1) for z in range(z+1) if
x+y+z!=n ])
UnboundLocalError: local variable 'y' referenced before assignment

我只是好奇我做错了什么。我可能在 Python3 中遗漏了一些东西,尽管它在 python2 中工作得很好。谢谢。

最佳答案

由于 x yz 在列表理解中被定义为“局部”变量,Python 3 将它们视为这样,并且不会'使用/查看全局值。

Python 2 没有这种区别(因此有些人在退出理解时观察到变量“泄漏”)并且它的行为与使用普通循环完全一样

这里有更好的解释:Python list comprehension rebind names even after scope of comprehension. Is this right?

真正有趣的是 python 首先提示 y 而不是 x。好吧,因为我很好奇,所以我在这里问了这个问题:why the UnboundLocalError occurs on the second variable of the flat comprehension?

这样做的正确方法是为循环索引使用不同的变量名称(不确定我选择的名称是否非常好,但至少无论 python 版本如何,这都有效):

ret_list = [ (x1,y1,z1) for x1 in range(x+1) for y1 in range(y+1) for z1 in range(z+1) if x1+y1+z1!=n ]

关于python - python2 中的理解列表工作正常,但我在 python3 中遇到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52719472/

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