Python 3 个变量并行赋值

问题描述 投票:0回答:1

我的问题来自一个流行的编码测试。

给定一条链定义如下

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

如果我们想恢复链条,例如:

输入:1->2->3->4->5->NULL

输出:5->4->3->2->1->NULL

可以这样解决这个

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur, pre = head, None
        while cur:
            tmp = cur.next 
            cur.next = pre 
            pre = cur      
            cur = tmp     
        return pre

但是有更紧凑的方式,我无法真正遵循:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur, pre = head, None
        while cur:
            cur.next, pre, cur = pre, cur, cur.next
        return pre

因为如果我将并行赋值线更改为

            pre, cur, cur.next = cur, cur.next, pre

它将不再正常工作。

我想知道python的并行赋值是如何工作的,特别是在所有3个变量都是动态的情况下。

python python-3.x variable-assignment iterable-unpacking
1个回答
7
投票

当你写并行作业时

x, y, z = a, b, c

相当于

temp = (a, b, c)
x = temp[0]
y = temp[1]
z = temp[2]

所以在失败的版本中,它相当于

temp = (cur, cur.next, pre)
pre = temp[0]
cur = temp[1]
cur.next = temp[2]

将此与工作版本进行比较:

cur.next = temp[0]
pre = temp[1]
cur = temp[2]

不同之处在于,在您的版本中,您分配给

cur.next
after,您已将
cur
步进到
cur.next
,因此您实际上分配给原始
cur.next.next

© www.soinside.com 2019 - 2024. All rights reserved.