問題:
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