[英]Python: local variable not recognized
我是 python 新手,我正在嘗試實現一個反轉鏈接列表的函數。
我收到錯誤消息:分配前引用了局部變量“new_head”
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None or head.next == None:
return head
new_head = None
def recur(curr_head):
if curr_head == None:
return
next_node = curr_head.next
curr_head.next = new_head
new_head = curr_head
recur(next_node)
recur(head)
return new_head
以下實現有效,但非常難看,是否有替代方法?
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None or head.next == None:
return head
new_head = None
arr = [new_head]
def recur(curr_head):
if curr_head == None:
return
temp = curr_head.next
curr_head.next = arr[0]
arr[0] = curr_head
recur(temp)
recur(head)
return arr[0]
在函數recur
的開頭,您可以輸入:
nonlocal new_head
這允許內部函數recur
修改在外部函數作用域中聲明的變量。
(這就像您需要使用global
來允許函數修改模塊范圍變量的方式。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.