怎么理解Python交换:为什么a,b=b,a并不总是等同于b,a=a,b?
我们都知道,在python中交换两个项目中a和b值的方法是:
a, b = b, a
它应该等同于:
b, a = a, b
但是,当我在敲代码时,我发现以下两种交换得到了不同的结果:
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交换中,这两个赋值是同时且独立发生的。
回答:
assignment statement
An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.
Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2]:
python">x = [0, 1]
i = 0
i, x[i] = 1, 2 # i is updated, then x[i] is updated
print(x)
assginment 先计算右侧得到一个 tuple ,然后将 tuple 中的值依次赋值给左侧的变量。
回答:
可以参考下这篇回答:https://stackoverflow.com/que...
简单地讲:
python3">nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
这种复制并不是同时发生的。它是先按从左往右的顺序计算右边两个变量的值,将结果临时保存在栈中,再按从左往右的顺序依次赋值给左边的变量。从实际运行的顺序来说,可以分成5步:
- 计算nums[nums[i]-1],将结果临时存入栈顶
- 计算num[i],将结果存入栈顶
- 将栈顶前面两个数据进行交换
- 将栈顶结果取出,赋值给nums[i]
- 将栈顶结果取出,赋值给nums[nums[i]-1],注意此时经过第4步,nums[i]的结果已经改变了。
回答:
a, b = b, a# 等同于
tmp1 = b
tmp2 = a
a = tmp1
b = tmp2
拆分成普通赋值就容易理解了
nums = [1, 2, 4, 3]i = 2
# nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
num1 = nums[nums[i]-1]
num2 = nums[i]
nums[i] = num1
nums[nums[i]-1] = num2
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]
num1 = nums[i]
num2 = nums[nums[i]-1]
nums[nums[i]-1] = num1
nums[i] = num2
print(nums)
# [1, 2, 3, 4]
因为 nums[nums[i]-1]
的指向会受 nums[i]
变化的影响,所以 nums[nums[i]-1]
必须先赋值,然后再赋值 nums[i]
以上是 怎么理解Python交换:为什么a,b=b,a并不总是等同于b,a=a,b? 的全部内容, 来源链接: utcz.com/p/938518.html