猿问

Python 中多重赋值背后的机制

我们都知道多重赋值可以一次赋值多个变量,在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

看来 in 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 中多重赋值背后的机制,以及对此的最佳实践是什么,临时变量是唯一的方法?


胡说叔叔
浏览 151回答 1
1回答

交互式爱情

a, b = c, d相当于temp = (c, d)a = temp[0]  # Expression a is evaluated here, not earlierb = temp[1]  # Expression b is evaluated here, not earlier就我个人而言,我建议使用您展示的临时变量明确地编写复杂的赋值。另一种方法是仔细选择赋值中元素的顺序:nums[nums[0]], nums[0] = nums[0], nums[nums[0]]改变nums如您所愿。
随时随地看视频慕课网APP

相关分类

Python
我要回答