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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章