为了账号安全,请及时绑定邮箱和手机立即绑定

Python 中多重赋值背后的机制

Python 中多重赋值背后的机制

胡说叔叔 2021-12-17 15:36:27
我们都知道多重赋值可以一次赋值多个变量,在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, incorrectnums = [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, incorrectpre = cur.nextpost = cur.next.nextcur.next, post.next, pre.next = post, pre, post.next# with temporary variable, correct所以我想知道Python 中多重赋值背后的机制,以及对此的最佳实践是什么,临时变量是唯一的方法?
查看完整描述

1 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

a, b = c, d

相当于


temp = (c, d)

a = temp[0]  # Expression a is evaluated here, not earlier

b = temp[1]  # Expression b is evaluated here, not earlier

就我个人而言,我建议使用您展示的临时变量明确地编写复杂的赋值。


另一种方法是仔细选择赋值中元素的顺序:


nums[nums[0]], nums[0] = nums[0], nums[nums[0]]

改变nums如您所愿。


查看完整回答
反对 回复 2021-12-17
  • 1 回答
  • 0 关注
  • 149 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号