gpt4 book ai didi

python - 奇怪的内联赋值

转载 作者:太空狗 更新时间:2023-10-30 00:39:31 24 4
gpt4 key购买 nike

我在 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, 1, 2, 2 , 3, 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 的任何赋值)。

关于python - 奇怪的内联赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33500567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com