comprehension list in python2 works fine but i get

2019-06-25 23:37发布

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)

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

I am just curious what I am doing wrong. I might be missing something in Python3 although it works fantastic in python2. Thank you.

1条回答
狗以群分
2楼-- · 2019-06-26 00:17

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 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

This is better explained here: Python list comprehension rebind names even after scope of comprehension. Is this right?

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?

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 ]
查看更多
登录 后发表回答