问题:
As we all know, the pythonic way to swap the values of two items a
and b
is众所周知,交换a
和b
两项值的 Pythonic 方法是
a, b = b, a
and it should be equivalent to它应该相当于
b, a = a, b
However, today when I was working on some code, I accidentally found that the following two swaps give different results:但是,今天在写代码的时候,无意中发现下面的两个swap给出了不同的结果:
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]
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 交换中,这两个任务同时且独立地发生。
解决方案:
参考一: https://en.stackoom.com/question/4bxda参考二: https://stackoom.com/question/4bxda