元组解包订单更改分配的值 [英] Tuple unpacking order changes values assigned

查看:91
本文介绍了元组解包订单更改分配的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为两者完全相同。

nums = [1, 2, 0]    
nums[nums[0]], nums[0] = nums[0], nums[nums[0]]    
print nums  # [2, 1, 0]

nums = [1, 2, 0]    
nums[0], nums[nums[0]] = nums[nums[0]], nums[0]    
print nums  # [2, 2, 1] 

但结果不同。

为什么结果不同? (为什么会产生第二个?)

But the results are different.
Why are the results different? (why is the second one that result?)

推荐答案

先决条件 - 2个重点




  • 列表是可变的

    Prerequisites - 2 important Points

    • Lists are mutable

      主要部分在列表中列表是可变的。这意味着可以更改列表的
      值。这就是你面临麻烦的
      的原因之一。 请参阅文档了解更多信息

      The main part in lists is that lists are mutable. It means that the values of lists can be changed. This is one of the reason why you are facing the trouble. Refer the docs for more info

      评估顺序

      另一部分是在解包元组时,评估从左到右开始
      请参阅文档了解更多信息

      The other part is that while unpacking a tuple, the evaluation starts from left to right. Refer the docs for more info

      你做 a,b = c,d c d 。然后从左侧开始, a 的值首先更改为 c ,然后是<$的值c $ c> b 更改为 d

      when you do a,b = c,d the values of c and d are first stored. Then starting from the left hand side, the value of a is first changed to c and then the value of b is changed to d.

      这里的问题是,如果在更改<的值时对 b 的位置有任何副作用code> a ,然后 d 分配给以后 b ,这是 b a 的副作用影响。

      The catch here is that if there are any side effects to the location of b while changing the value of a, then d is assigned to the later b, which is the b affected by the side effect of a.

      现在出现问题

      在第一种情况下,

      nums = [1, 2, 0]    
      nums[nums[0]], nums[0] = nums[0], nums[nums[0]]    
      

      nums [0] 最初是 1 nums [nums [0]] 2 因为它的计算结果为 nums [1] 。因此1,2现在存储在内存中。

      nums[0] is initially 1 and nums[nums[0]] is 2 because it evaluates to nums[1]. Hence 1,2 is now stored into memory.

      现在元组解包从左侧发生,所以

      Now tuple unpacking happens from left hand side, so

      nums[nums[0]] = nums[1] = 1   # NO side Effect. 
      nums[0] = 2
      

      因此打印nums 将打印 [2,1,0]

      但在这种情况下

      nums = [1, 2, 0]   
      nums[0], nums[nums[0]] = nums[nums[0]], nums[0]    
      

      nums [nums [0]] ,nums [0] 将2,1放在堆栈上,就像第一种情况一样。

      nums[nums[0]], nums[0] puts 2,1 on the stack just like the first case.

      但是在左侧,那是 nums [0],nums [nums [0]] ,更改 nums [0] 有副作用,因为它被用作 nums [nums [0]] 。因此

      However on the left hand side, that is nums[0], nums[nums[0]], the changing of nums[0] has a side effect as it is used as the index in nums[nums[0]]. Thus

      nums[0] = 2
      nums[nums[0]] = nums[2] = 1  # NOTE THAT nums[0] HAS CHANGED
      

      nums [1] 保持不变,价值 2 。因此打印nums 将打印 [2,2,1]

      nums[1] remains unchanged at value 2. hence print nums will print [2, 2, 1]

      这篇关于元组解包订单更改分配的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆