在 python3 中交换列表中的两个元素时出现非常奇怪的行为

very strange behavior when swap two elements in the list in python3

我有一个列表

a = [-1,4,3,1]

我们有

a[1] = 4
a[3] = 1

现在我想交换 a[1]a[3]

以下代码运行良好:

a[1], a[3]  = a[3], a[1]

但是如果我使用:

a[1], a[a[1]-1] = a[a[1]-1], a[1]

它给了我:

 a = [4,1,3,1]

答案不正确。自从我们知道 a[1] - 1 = 3 以来,这里发生了什么。任何想法,谢谢。

这与 Multiple assignment and evaluation order in Python 基本上是同一个问题,但由于复杂的索引而出现了表面皱纹。

注意事项:

  • 右侧在左侧完全被评估之前被完全评估

  • 元组赋值完全从左到右求值

文档在这里(尽管很少)说明了这一点:https://docs.python.org/3/reference/expressions.html#evaluation-order

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

在这里,我将根据您的情况说明这些规则:

State of a Evaluation of expression Comment [-1, 4, 3, 1] a[1], a[a[1]-1] = a[a[1]-1], a[1] <start> [-1, 4, 3, 1] a[1], a[a[1]-1] = a[4-1], a[1] a[1] resolves to 4 [-1, 4, 3, 1] a[1], a[a[1]-1] = a[3], a[1] 4-1 is 3 [-1, 4, 3, 1] a[1], a[a[1]-1] = 1, a[1] a[3] resolves to 1 [-1, 4, 3, 1] a[1], a[a[1]-1] = 1, 4 a[1] resolves to 4 [-1, 1, 3, 1] a[a[1]-1] = 4 a[1] = 1 assigned [-1, 1, 3, 1] a[1-1] = 4 a[1] resolves to 1 [-1, 1, 3, 1] a[0] = 4 1-1 is 0 [4, 1, 3, 1] a[0] = 4 assigned