理解 Python 交换:为什么 a, b = b, a 并不总是等价于 b, a = a, b? [英] Understand Python swapping: why is a, b = b, a not always equivalent to b, a = a, b?
问题描述
众所周知,交换a
和b
两项值的pythonic方式是
As we all know, the pythonic way to swap the values of two items a
and b
is
a, b = b, a
它应该等价于
b, a = a, b
然而,今天我在做一些代码的时候,无意中发现以下两个交换给出了不同的结果:
However, today when I was working on some code, I accidentally found that the following two swaps give different results:
nums = [1, 2, 4, 3]
i = 2
nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
print(nums)
# [1, 2, 4, 3]
nums = [1, 2, 4, 3]
i = 2
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
print(nums)
# [1, 2, 3, 4]
这对我来说令人难以置信.有人可以向我解释这里发生了什么吗?我认为在 Python 交换中,两个分配同时且独立地发生.
This is mind-boggling to me. Can someone explain to me what happened here? I thought in a Python swap the two assignments happen simultaneously and independently.
推荐答案
来自 python.org
将对象分配给目标列表(可选地括在圆括号或方括号中)的递归定义如下.
Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.
...
- Else:对象必须是与目标列表中的目标数量相同的可迭代对象,并且项目从左到右分配给相应的目标.
所以我认为这意味着你的任务
So I interpret that to mean that your assignment
nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
大致相当于
tmp = nums[nums[i]-1], nums[i]
nums[i] = tmp[0]
nums[nums[i] - 1] = tmp[1]
(当然还有更好的错误检查)
(with better error-checking, of course)
而另一个
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
就像
tmp = nums[i], nums[nums[i]-1]
nums[nums[i] - 1] = tmp[0]
nums[i] = tmp[1]
所以在两种情况下都会首先评估右侧.但是然后左边的两块按顺序求值,求值后立即赋值.至关重要的是,这意味着左侧的第二项仅在第一项分配已经完成后进行评估.因此,如果您先更新 nums[i]
,那么 nums[nums[i] - 1]
引用的索引不同于更新 nums[i]]
秒.
So the right-hand side is evaluated first in both cases. But then the two pieces of the left-hand side are evaluated in order, and the assignments are done immediately after evaluation. Crucially, this means that the second term on the left-hand side is only evaluated after the first assignment is already done. So if you update nums[i]
first, then the nums[nums[i] - 1]
refers to a different index than if you update nums[i]
second.
这篇关于理解 Python 交换:为什么 a, b = b, a 并不总是等价于 b, a = a, b?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!