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

标签 python tuples variable-assignment

a, a = 2, 1

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

当我们不只有 a 时,问题就变得相关了,但是 a[i]、a[j] 和 i 和 j 可能相等也可能不相等。

最佳答案

是的,元组分配必须从左到右进行,这是 python 语言引用的一部分。

https://docs.python.org/2.3/ref/assignment.html

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

所以所有的 Python 实现都应该遵循这个规则(正如另一个答案中的实验所证实的那样)。

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

关于python - python元组赋值顺序是固定的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39855410/

相关文章:

Python赋值命令语法

python - Sklearn,网格搜索 : how to print out progress during the execution?

python - 打开 CV 或用于后处理识别的替代方法

typescript - 为什么 Typescript 映射元组类型在提供通用类型与直接类型时表现不同?

list - 如何更新 Haskell 列表中的特定元组?

c - 在结构中初始化结构?

c# - 为枚举分配(非)常量值

python - 使用 Python 脚本激活 virtualenv

python - 在 groupby 之后对 Pandas 分类标签进行排序

python - Python 3.6 中带有元组的格式化字符串文字