多重赋值语句,不是说x=y, y=x+y=y+y,而是把右边的变量赋给临时变量后,再做赋值(In an assignment statement, the right-hand side is always evaluated fully before doing the actual setting of variables):
x, y = y, x + y
等价于:
ham = y
spam = x + y
x = ham
y = spam
比如反转列表, 都不用考虑临时变量的存储,因为多重赋值语句自动帮我们存了:
def reverseList(self, head):
cur, pre = head, None
while cur:
cur.next, prev, cur = pre, cur, cur.next
return prev
此外以下赋值语句也关注一下:
a, a[0] = [1], 2
# a == [2]
网友评论