使用 += 但不附加列表时出现 UnboundLocalError
UnboundLocalError while using += but not append list
不太明白下面两个类似代码的区别:
def y(x):
temp=[]
def z(j):
temp.append(j)
z(1)
return temp
呼叫 y(2)
returns [1]
def y(x):
temp=[]
def z(j):
temp+=[j]
z(1)
return temp
呼叫 y(2)
returns UnboundLocalError: local variable 'temp' referenced before assignment
。为什么 +
运算符会产生错误?谢谢
回答标题,+和"append"的区别是:
[11, 22] + [33, 44,]
会给你:
[11, 22, 33, 44]
和.
b = [11, 22, 33]
b.append([44, 55, 66])
会给你
[11, 22, 33 [44, 55, 66]]
错误答案
This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope
这里的问题是temp+=[j]
等于temp = temp +[j]
。临时变量在赋值之前在这里读取。这就是为什么它会出现这个问题。这实际上包含在 python 常见问题解答中。
如需进一步阅读,请单击 here。 :)
出现 UnboundLocalError
是因为,当您对范围内的变量进行赋值时,Python 会自动认为该变量是该范围的 本地变量 并隐藏任何外部范围内任何类似命名的变量。
在 append
函数中,您没有进行赋值 本身 ,因此没有作用域错误。
不太明白下面两个类似代码的区别:
def y(x):
temp=[]
def z(j):
temp.append(j)
z(1)
return temp
呼叫 y(2)
returns [1]
def y(x):
temp=[]
def z(j):
temp+=[j]
z(1)
return temp
呼叫 y(2)
returns UnboundLocalError: local variable 'temp' referenced before assignment
。为什么 +
运算符会产生错误?谢谢
回答标题,+和"append"的区别是:
[11, 22] + [33, 44,]
会给你:
[11, 22, 33, 44]
和.
b = [11, 22, 33]
b.append([44, 55, 66])
会给你
[11, 22, 33 [44, 55, 66]]
错误答案
This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope
这里的问题是temp+=[j]
等于temp = temp +[j]
。临时变量在赋值之前在这里读取。这就是为什么它会出现这个问题。这实际上包含在 python 常见问题解答中。
如需进一步阅读,请单击 here。 :)
出现 UnboundLocalError
是因为,当您对范围内的变量进行赋值时,Python 会自动认为该变量是该范围的 本地变量 并隐藏任何外部范围内任何类似命名的变量。
在 append
函数中,您没有进行赋值 本身 ,因此没有作用域错误。