(没有询问该问题的解决方案,只是试图了解错误)
我收到以下错误
UnboundLocalError: local variable new_list referenced before assignment
在尝试运行这段代码时。我的逻辑是“如果new_list
不存在,则创建new_list
,否则使用分配new_list.next
,但看起来在这种情况下不起作用。
有人可以向我解释原因,我应该怎么做才能解决此错误?
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
temp = 0
while l1 or l2:
if l1 and l2:
new_val = (l1.val + l2.val) % 10 + temp
new_node = ListNode(new_val)
if l1:
new_node = ListNode(l1.val + temp)
if l2:
new_node = ListNode(l2.val + temp)
if not new_list:
new_list = new_node
else:
new_list.next = new_node
if new_val and new_val > 9:
temp = 1
else:
temp = 0
return new_list
答案 0 :(得分:0)
当l1
和l2
都为 f 时,while
循环不会运行,并且您的函数直接进入return new_list
-点名称new_list
尚未绑定到任何对象,即尚未分配给对象。
通常的解决方法是在new_list
循环之前将while
设置为默认值,例如:
def addTwoNumbers(self, l1, l2):
temp = 0
# Here
new_list = []
while l1 or l2:
...
...
return new_list
您也可以像这样{@ 1}早点>>
return