一行中的 Python 多个赋值语句 [英] Python Multiple Assignment Statements In One Line
问题描述
(别担心,这不是关于解包元组的另一个问题.)
在python中,像foo = bar = baz = 5
这样的语句将变量foo、bar和baz赋值为5.它从左到右将这些变量赋值,正如nastier所证明的像
但是 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. Infoo = bar = 5
, there are two(target_list "=")
productions, and theexpression_list
part is just5
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屋!