Python的逗号运算符在分配期间如何工作? [英] How does Python's comma operator works during assignment?

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

问题描述

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



在此引用:


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


阅读后,我想到写一个类似

  a = 5 
b = 4
a,b = a + b,a
打印a,b

我的假设是a和b的值都应为9。 / p>

但是,事实证明我错了。 a的值为9,而 b的值为5。



有人可以帮助我更好地理解吗?为什么要分配旧值 a而不是新值?根据文档,将首先分配一个值?我缺少什么吗?

解决方案

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



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


第一行包含多个赋值:变量a和b同时获得新值0 1.在最后一行再次使用它,表明在执行任何赋值之前,首先对右侧的表达式进行了评估。右侧表达式是从左到右评估的。


强调我的想法。



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

  a,b = 5 + 4,5 
打印a,b


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

In that it is quoted that:

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

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

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

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.

From the Python tutorial: First steps towards programming:

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.

Emphasis mine.

Your code is functionally equivalent to the following:

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

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

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