4

当在 Python 中使用多重赋值时,例如

a, b, c = b, c, a

我一直认为论点的相对顺序是无关紧要的(只要双方一致),即如果这样做,结果将是相同的

c, a, b = a, b, c

虽然当a, b, c它们是自变量时这似乎是正确的,但当它们相关时,它似乎可能不正确。

例如,如果我们定义一个链表的节点如下:

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

并编写一个函数来就地反转链表:

def reverseList(head):
    """
    :type head: ListNode
    :rtype: ListNode
    """
    if head is None:
        return head
    slow = None
    fast = head
    while fast is not None:
        fast.next, slow, fast = slow, fast, fast.next

    return slow

那么这工作正常,例如:

head = ListNode(1)
head.next = ListNode(2)
reverseList(head)

但是,如果我们用不同的赋值顺序替换循环中的行:

fast, fast.next, slow = fast.next, slow, fast  

然后我们得到一个错误

AttributeError: 'NoneType' object has no attribute 'next'

在第二次(最后一次)迭代中,两者fastslow都不是Nonefast.nextNone,但我仍然不明白为什么这会导致错误?多个作业不应该并行完成吗?

更一般地说,什么时候什么时候不能改变多重赋值语句的顺序而不影响结果?

编辑:我读过这个问题,虽然它是相关的,但我仍然不明白那里的答案如何帮助解释我的问题。我将不胜感激任何详细说明我的情况。

4

0 回答 0