python元组赋值顺序是固定的吗?

问题描述 投票:0回答:2

a, a = 2, 1

结果总是等于 1?换句话说,元组赋值是否保证是从左到右的?

当我们不仅有 a,而且 a[i]、a[j] 以及 i 和 j 可能相等也可能不相等时,这个问题就变得相关了。

python tuples variable-assignment
2个回答
10
投票

是的,这是Python语言参考的一部分,元组赋值必须从左到右进行。

https://docs.python.org/3/reference/simple_stmts.html#assignment-statements

赋值语句计算表达式列表(记住 这可以是单个表达式或逗号分隔的列表,后者 产生一个元组)并将单个结果对象分配给每个 目标列表,从左到右。

因此所有Python实现都应该遵循这个规则(正如其他答案中的实验所证实的那样)。

就我个人而言,我仍然会犹豫是否使用它,因为对于未来的代码读者来说似乎不清楚。


1
投票

它是如何工作的:

a, a = 2, 1
--> a does not exist, create variable a and set value to 2
--> a already exists, value of a changed to 1

当你有不同的变量时,它的工作方式完全相同:

a, b, a = 1, 2, 3
--> a does not exist, create variable a and set value to 1
--> b does not exist, create variable b and set value to 2
--> a already exists, value of a changed to 3
© www.soinside.com 2019 - 2024. All rights reserved.