奇怪的内联赋值

Strange inline assignment

我在 Python(2 和 3)中遇到这种奇怪的行为:

>>> a = [1, 2]
>>> a[a.index(1)], a[a.index(2)] = 2, 1

这导致:

>>> a
[1, 2]

但是如果你写

>>> a = [1, 2]
>>> a[a.index(1)], a[a.index(2)] = x, y

其中 x, y != 2, 1(可以是 1, 12, 23, 5 等),结果为:

>>> a == [x, y]
True

不出所料。为什么 a[a.index(1)], a[a.index(2)] = 2, 1 没有产生结果 a == [2, 1]

>>> a == [2, 1]
False

因为它实际上被解释成这样:

>>> a = [1, 2]
>>> a
[1, 2]
>>> a[a.index(1)] = 2
>>> a
[2, 2]
>>> a[a.index(2)] = 1
>>> a
[1, 2]

引用 standard rules for assignment(强调我的):

  • If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

a[a.index(1)](即 a[0])的赋值发生在 之前 第二个赋值要求 a.index(2),此时 a.index(2) == 0.

您将看到任何分配的相同行为:

foo = [a, b]
foo[foo.index(a)], foo[foo.index(b)] = x, y

其中 x == b(在这种情况下,右侧第一个值为 2 的任何赋值)。