元组拆包顺序更改分配的值 [英] Tuple unpacking order changes values assigned

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

问题描述

我认为两者是相同的.

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 个要点

  • 列表是可变的

    列表的主要部分是列表是可变的.这意味着列表的值可以更改.这就是你的原因之一面临困境.参考文档了解更多信息

    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 时,首先存储 cd 的值.然后从左边开始,先将a的值改为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.

    这里的问题是,如果在更改 a 的值时对 b 的位置有任何副作用,则 d 是分配给later b,也就是a的副作用影响到的b.

    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] 最初是 1nums[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
    

    因此 print 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.因此 print nums 将打印 [2, 2, 1]

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

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

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