【发布时间】:2021-07-02 13:03:32
【问题描述】:
我们都知道多重赋值可以一次赋值多个变量,这在swap中很有用。 在这种情况下效果很好:
nums = [2, 0, 1]
nums[0], nums[2] = nums[2], nums[0]
# nums=[1, 0, 2] directly, correct
,但在更复杂的情况下失败了,例如:
nums = [2, 0, 1]
nums[0], nums[nums[0]] = nums[nums[0]], nums[0]
# nums=[1, 2, 1] directly, incorrect
nums = [2, 0, 1]
tmp = nums[0]
nums[0], nums[tmp] = nums[tmp], nums[0]
# nums=[1, 0, 2] with temporary variable, correct
似乎在nums[nums[0]],nums[0] 将被分配之前,而不是一次。
在复杂的链表节点交换中也失败了,例如:
cur.next, cur.next.next.next, cur.next.next = cur.next.next, cur.next, cur.next.next.next
# directly, incorrect
pre = cur.next
post = cur.next.next
cur.next, post.next, pre.next = post, pre, post.next
# with temporary variable, correct
所以我想知道Python中多重赋值背后的机制,什么是最佳实践,临时变量是唯一的方法?
【问题讨论】:
-
这是评估顺序的问题。两侧订阅相同数组的赋值中的求值顺序没有明显的顺序。这样
c, b = b, c与a = b, c; c, b = a不同。我希望我能记住还有哪个问题涵盖了这一点。
标签: python