元组解包订单更改分配的值 [英] Tuple unpacking order changes values assigned
问题描述
我认为两者完全相同。
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 $的值首先存储c $ c>。然后从左侧开始,
更改为a
的值首先更改为c
,然后是<$的值c $ c> bd
。when you do
a,b = c,d
the values ofc
andd
are first stored. Then starting from the left hand side, the value ofa
is first changed toc
and then the value ofb
is changed tod
.这里的问题是,如果在更改<的值时对
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 ofa
, thend
is assigned to the laterb
, which is theb
affected by the side effect ofa
.现在出现问题
在第一种情况下,
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 initially1
andnums[nums[0]]
is2
because it evaluates tonums[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]] $ c $中的索引C>。因此
However on the left hand side, that is
nums[0], nums[nums[0]]
, the changing ofnums[0]
has a side effect as it is used as the index innums[nums[0]]
. Thusnums[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 value2
. henceprint nums
will print[2, 2, 1]
这篇关于元组解包订单更改分配的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!