繁体   English   中英

Python:无法识别局部变量

[英]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来允许函数修改模块范围变量的方式。)

Python 文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM