一行中的 Python 多个赋值语句 [英] Python Multiple Assignment Statements In One Line

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

问题描述

(别担心,这不是关于解包元组的另一个问题.)

在python中,像foo = bar = baz = 5这样的语句将变量foo、bar和baz赋值为5.它从左到右将这些变量赋值,正如nastier所证明的像

这样的例子<预><代码>>>>foo[0] = foo = [0]回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中NameError: 名称 'foo' 未定义>>>foo = foo[0] = [0]>>>富[[...]]>>>富[0][[...]]>>>foo 是 foo[0]真的

但是 python 语言参考指出赋值语句的形式为

(target_list "=")+ (expression_list | yield_expression)

在赋值时,expression_list 首先被求值,然后赋值发生.

既然 bar = 5 不是 expression_list,那么行 foo = bar = 5 怎么可能有效?如何解析和评估一行上的这些多个分配?我读错了语言参考吗?

解决方案

感谢@MarkDickinson,他在评论中回答了这个问题:

<块引用>

注意(target_list "=")+中的+,表示一份或多份.在foo = bar = 5中,有两个(target_list "=")产生式,而expression_list部分就是5

赋值语句中的所有 target_list 产生式(即看起来像 foo = 的东西)从左到右分配给 expression_list 在语句的右端,在 expression_list 被求值之后.

当然,通常的元组解包"赋值语法也适用于这种语法,让您可以执行诸如

<预><代码>>>>foo, boo, moo = boo[0], moo[0], foo[0] = moo[0], foo[0], boo[0] = [0], [0], [0]>>>富[[[[[...]]]]]>>>foo[0] 是嘘真的>>>foo[0][0] 是 moo真的>>>foo[0][0][0] 是 foo真的

(Don't worry, this isn't another question about unpacking tuples.)

In python, a statement like foo = bar = baz = 5 assigns the variables foo, bar, and baz to 5. It assigns these variables from left to right, as can be proved by nastier examples like

>>> foo[0] = foo = [0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> foo = foo[0] = [0]
>>> foo
[[...]]
>>> foo[0]
[[...]]
>>> foo is foo[0]
True

But the python language reference states that assignment statements have the form

(target_list "=")+ (expression_list | yield_expression)

and on assignment the expression_list is evaluated first and then the assigning happens.

So how can the line foo = bar = 5 be valid, given that bar = 5 isn't an expression_list? How are these multiple assignments on one line getting parsed and evaluated? Am I reading the language reference wrong?

解决方案

All credit goes to @MarkDickinson, who answered this in a comment:

Notice the + in (target_list "=")+, which means one or more copies. In foo = bar = 5, there are two (target_list "=") productions, and the expression_list part is just 5

All target_list productions (i.e. things that look like foo =) in an assignment statement get assigned, from left to right, to the expression_list on the right end of the statement, after the expression_list gets evaluated.

And of course the usual 'tuple-unpacking' assignment syntax works within this syntax, letting you do things like

>>> foo, boo, moo = boo[0], moo[0], foo[0] = moo[0], foo[0], boo[0] = [0], [0], [0]
>>> foo
[[[[...]]]]
>>> foo[0] is boo
True
>>> foo[0][0] is moo
True
>>> foo[0][0][0] is foo
True

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

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