How can I avoid this “variable referenced before assignment”?
本问题已经有最佳答案,请猛点这里访问。
遇到以下问题。这可能是一个简单的解决方案,可能以前这里有人问过,但我找不到。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def a(): liA = [] def b(): for i in liA: i += 1 liB = generateList() for i in liB: i -= 1 liA = liB def generateList(): return [1,2,3,4] b() a() |
UnboundLocalError:在赋值之前引用了局部变量"lia"
因此,您应该按照以下方式编辑代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def a(): liA = [] def b(liA): for i in liA: i += 1 liB = generateList() for i in liB: i -= 1 liA = liB def generateList(): return [1,2,3,4] b(liA) a() |
希望我帮了你!
如果您查看整个堆栈跟踪,就可以更好地了解错误是如何发生的。
1 2 3 4 5 6 7 8 | Traceback (most recent call last): File"/Users/jwp/Desktop/junk.py3", line 16, in <module> a() File"/Users/jwp/Desktop/junk.py3", line 14, in a b() File"/Users/jwp/Desktop/junk.py3", line 4, in b for i in liA: UnboundLocalError: local variable 'liA' referenced before assignment |
因此,当您调用
最明显的答案是把
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def a(): liA = [] def b(inlist): liA = inlist for i in liA: i += 1 liB = generateList() for i in liB: i -= 1 liA = liB def generateList(): return [1,2,3,4] b(liA) a() |
这能满足你的需要吗?