我們都知道多重賦值可以一次賦值多個變量,在swap中很有用。它在這種情況下運行良好:nums = [2, 0, 1]nums[0], nums[2] = nums[2], nums[0]# nums=[1, 0, 2] directly, correct,但它在更復雜的情況下失敗,例如:nums = [2, 0, 1]nums[0], nums[nums[0]] = nums[nums[0]], nums[0]# nums=[1, 2, 1] directly, incorrectnums = [2, 0, 1]tmp = nums[0]nums[0], nums[tmp] = nums[tmp], nums[0]# nums=[1, 0, 2] with temporary variable, correct看來 in nums[nums[0]],nums[0]會在之前分配,而不是一次分配。它也在復雜的鏈表節點交換中失敗,例如:cur.next, cur.next.next.next, cur.next.next = cur.next.next, cur.next, cur.next.next.next# directly, incorrectpre = cur.nextpost = cur.next.nextcur.next, post.next, pre.next = post, pre, post.next# with temporary variable, correct所以我想知道Python 中多重賦值背后的機制,以及對此的最佳實踐是什么,臨時變量是唯一的方法?
1 回答

交互式愛情
TA貢獻1712條經驗 獲得超3個贊
a, b = c, d
相當于
temp = (c, d)
a = temp[0] # Expression a is evaluated here, not earlier
b = temp[1] # Expression b is evaluated here, not earlier
就我個人而言,我建議使用您展示的臨時變量明確地編寫復雜的賦值。
另一種方法是仔細選擇賦值中元素的順序:
nums[nums[0]], nums[0] = nums[0], nums[nums[0]]
改變nums如您所愿。
添加回答
舉報
0/150
提交
取消