Understand Python swapping: why is a, b = b, a not always equivalent to b, a = a, b?

问题:

As we all know, the pythonic way to swap the values of two items a and b is众所周知,交换ab两项值的 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章