python 3变量并行赋值
我的问题来自一个流行的编码测试 给定一条链: 如果要还原链,例如: 输入:1->2->3->4->5->NULL 输出:5->4->3->2->1->NULL 它可以通过如下方式解决: 但有一点,我不能真正理解:python 3变量并行赋值,python,python-3.x,variable-assignment,Python,Python 3.x,Variable Assignment,我的问题来自一个流行的编码测试 给定一条链: 如果要还原链,例如: 输入: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: cur.next
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个变量都是动态的情况下。当您编写并行赋值时
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]
所以在失败的版本中,它相当于
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
步进到cur.next
后,分配给cur.next
,因此实际上您将分配给原始的cur.next.next
每件事都首先在右侧求值,它实际上创建了一个长度为三的元组(虽然作为一个CPython实现细节/微优化,编译器实际上避免在2和3的情况下生成元组)。然后元组的项从左到右分配到左边的目标列表中。我不明白解释器实际上在做什么。它会在左边重复赋值吗?像a,uu,c,d[a]这样更复杂的解包是什么,a.next=tuple看起来像什么?是的,它就是这么做的。这和我在回答中所说的差不多。a=tuple[0];=tuple[1];c=tuple[2];d[a]=tuple[3];a.next=tuple[4]