元组拆包顺序更改分配的值 [英] 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 个要点
列表是可变的
列表的主要部分是列表是可变的.这意味着列表的值可以更改.这就是你的原因之一面临困境.参考文档了解更多信息
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
,然后将b
的值改为d
.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
.这里的问题是,如果在更改
a
的值时对b
的位置有任何副作用,则d
是分配给laterb
,也就是a
的副作用影响到的b
.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
因此
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 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
.因此print nums
将打印[2, 2, 1]
nums[1]
remains unchanged at value2
. henceprint nums
will print[2, 2, 1]
这篇关于元组拆包顺序更改分配的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!