而不是附加列表时出现UnboundLocalError

而不是附加列表时出现UnboundLocalError

本文介绍了使用+ =而不是附加列表时出现UnboundLocalError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太了解以下两个相似代码之间的区别:

I do not quite understand the difference between the following two similar codes:

def y(x):
    temp=[]
    def z(j):
        temp.append(j)
    z(1)
    return temp

调用y(2)返回[1]

def y(x):
    temp=[]
    def z(j):
        temp+=[j]
    z(1)
    return temp

调用y(2)返回UnboundLocalError: local variable 'temp' referenced before assignment.为什么+运算符会生成错误?谢谢

calling y(2) returns UnboundLocalError: local variable 'temp' referenced before assignment. Why + operator generates the error? Thanks

推荐答案

标题,+和"append"之间的区别是:

Answer to the heading, the difference between + and "append" is:

[11, 22] + [33, 44,]

会给您:

[11, 22, 33, 44]

和.

b = [11, 22, 33]
b.append([44, 55, 66])

会给你

[11, 22, 33 [44, 55, 66]]

回答错误

这里的问题是temp+=[j]等于temp = temp +[j].在分配变量之前,先在此处读取temp变量.这就是为什么它会导致此问题.实际上,这在python FAQ中已涉及.

The problem here is temp+=[j] is equal to temp = temp +[j]. The temp variable is read here before its assigned. This is why it's giving this problem. This is actually covered in python FAQ's.

有关更多信息,请点击此处. :)

For further readings, click here. :)

这篇关于使用+ =而不是附加列表时出现UnboundLocalError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:00