Python 中的同时赋值语义 [英] Simultaneous assignment semantics in Python

查看:46
本文介绍了Python 中的同时赋值语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 Python 3 代码:

a = [-1,-1,-1]我 = 0

现在考虑在 a 和 i 上同时赋值的以下两个版本:

作业版本 1:

a[i],i = i,i+1

作业版本 2:

i,a[i] = i+1,i

我希望这两个版本的同时赋值在语义上是等效的.但是,如果您在每次同时赋值后检查 a 和 i 的值,则会得到不同的状态:

分配版本 1 后 print(a,i) 的输出:

[0, -1, -1] 1

分配版本 2 后 print(a,i) 的输出:

[-1, 0, -1] 1

我不是 Python 语义方面的专家,但这种行为似乎很奇怪.我希望两个作业都像作业版本 1 一样.此外,如果您检查以下链接,您会希望两个作业版本都指向相同的状态:

关于同时分配的 Python 语义,我有什么遗漏吗?

注意:这种奇怪的行为似乎无法重现,例如,当变量 a 具有整数类型时;它似乎要求 a 是列表类型(也许任何可变类型都是这种情况?).

在这种情况下:

i, a[i] = i + 1, i

右侧的计算结果为元组 (1, 0).然后这个元组被解包到 ia[i].a[i] 在解包过程中被评估,而不是在之前,所以对应于 a[1].

由于在任何解包发生之前对右侧进行评估,因此在右侧引用 a[i] 将始终是 a[0],无论最终结果如何i

的值

这是另一个无用的有趣例子供您锻炼

<预><代码>>>>a = [0,0,0,0]>>>i, a[i], i, a[i] = range(4)>>>一种[1, 0, 3, 0]

Consider the following Python 3 code:

a = [-1,-1,-1]
i = 0

And now consider the following two versions of a simultaneous assignment over both a and i:

Assignment version 1:

a[i],i = i,i+1

Assignment version 2:

i,a[i] = i+1,i

I would expect these two versions of simultaneous assignments to be semantically equivalent. However, if you check the values of a and i after each one of the simultaneous assignments, you get different states:

Output for print(a,i) after assignment version 1:

[0, -1, -1] 1

Output for print(a,i) after assignment version 2:

[-1, 0, -1] 1

I am not an expert on Python's semantics, but this behaviour seems weird. I would expect both assignments to behave as assignment version 1. Moreover, if you check the following link, one would expect both assignment versions to lead to the same state:

Link to book excerpt in Google Books

Is there something I am missing regarding Python semantics for simultaneous assignments?

Note: This weird behaviour does not seem to be reproducible, for instance, when the variable a has integer type; it seems to require a to be of type list (maybe this is the case for any mutable type?).

解决方案

In this case:

i, a[i] = i + 1, i

The righthand side evaluates to a tuple (1, 0). This tuple is then unpacked to i and then a[i]. a[i] is evaluated during the unpacking, not before, so corresponds to a[1].

Since the righthand side is evaluated before any unpacking takes place, referring to a[i] on the righthand side would always be a[0] regardless of the final value of i

Here is another useless fun example for you to work out

>>> a = [0,0,0,0]
>>> i, a[i], i, a[i] = range(4)
>>> a
[1, 0, 3, 0]

这篇关于Python 中的同时赋值语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆