Python 的逗号运算符在赋值过程中是如何工作的? [英] How does Python's comma operator work during assignment?

查看:24
本文介绍了Python 的逗号运算符在赋值过程中是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Python 文档中的赋值语句(http://docs.python.org/reference/simple_stmts.html#assignment-statements).

I was reading the assignment statements in the Python docs ( http://docs.python.org/reference/simple_stmts.html#assignment-statements ).

其中引用的是:

如果目标是括在圆括号或方括号中的目标列表:该对象必须是具有与目标列表中的目标相同数量的项目的可迭代对象,并且其项目从左到右分配,到相应的目标.

If the target is a target list enclosed in parentheses or in square brackets: The object must be an iterable with the same number of items as there are targets in the target list, and its items are assigned, from left to right, to the corresponding targets.

看完之后,我想写一个这样的例子:

After reading it, I thought of writing a sample like this:

a = 5
b = 4
a, b = a + b, a
print a, b

我的假设是 a 和 b 的值都应该是 9.

My assumption was that a and b both should have the value of 9.

然而,事实证明我错了.'a' 的值为 9,'b' 的值为 5.

However, I am proven wrong. 'a' has the value of 9 and 'b' has the value of 5.

有人可以帮助我更好地理解这一点吗?为什么分配了旧值 'a' 而不是新值?根据文档,首先会分配 a 的值,对吗?我错过了什么吗?

Can some one help me understand this better? Why the older value of 'a' is assigned rather than the new one? As per the docs, a's value will be assigned first right? Am I missing something?

推荐答案

赋值运算符右侧的所有表达式都会在进行任何赋值之前求值.

All the expressions to the right of the assignment operator are evaluated before any of the assignments are made.

来自 Python 教程:编程的第一步:

第一行包含一个多重赋值:变量 a 和 b 同时获得新值 0 和 1.在最后一行再次使用它,证明 右侧的表达式都已计算在进行任何任务之前.右侧表达式从左到右求值.

The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

强调我的.

您的代码在功能上等同于以下内容:

Your code is functionally equivalent to the following:

a, b = 5 + 4, 5
print a, b

这篇关于Python 的逗号运算符在赋值过程中是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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