python2中的理解列表工作正常,但是我在python3中收到错误
使用综合列表,我有以下代码:
I have the following code using the comprehensive list:
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中,出现以下错误:
in python2 works as expected. However in python3 i get the following error:
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中效果很好.谢谢.
I am just curious what I am doing wrong. I might be missing something in Python3 although it works fantastic in python2. Thank you.
由于在列表理解中将x
y
和z
定义为局部"变量,因此Python 3认为它们是这样,并且不会.不要使用/查看全局值.
Since x
y
and z
are defined as "local" variables in the list comprehension, Python 3 considers them as such, and doesn't use/see the global value.
Python 2没什么区别(因此退出理解时有些人会观察到变量"leak"),并且其行为与使用常规循环时完全一样
Python 2 doesn't make that difference (hence the variable "leak" that some have observed when exiting a comprehension) and it behaves exactly like if you used normal loops
这在这里有更好的解释: Python列表理解甚至在理解范围之后也会重新绑定名称.是这样吗?
This is better explained here: Python list comprehension rebind names even after scope of comprehension. Is this right?
真正有趣的是python首先抱怨y
而不是x
.好吧,由于我很好奇,我在这里问了这个问题:
What is really funny is that python complains about y
first and not x
. Well, since I'm curious I've asked this question here: why the UnboundLocalError occurs on the second variable of the flat comprehension?
执行此操作的正确方法是为循环索引使用不同的变量名称(不确定我选择的名称是否很好,但是至少不管python版本如何,它都可以工作):
The proper way to do this is to use different variable names for your loop indices (not sure if the names I chose are very good, but at least this works regardless of the python version):
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 ]