问题描述
以下 Python 表达式有什么区别:
# 首先:x,y = y,x+y# 第二:x = yy = x+y
First 与 Second 给出的结果不同.
例如
首先:
>>>x = 1>>>y = 2>>>x,y = y,x+y>>>X2>>>是3第二:
>>>x = 1>>>y = 2>>>x = y>>>y = x+y>>>X2>>>是4y 在 First 中是 3,在 Second
中是 4在赋值语句中,总是在实际设置变量之前对右侧进行全面评估.所以,
x, y = y, x + y
评估y
(我们称结果为ham
),评估x + y
(称其为spam
), then 将 x
设置为 ham
,将 y
设置为 spam
.也就是说,就像
ham = y垃圾邮件 = x + yx = 火腿y = 垃圾邮件
相比之下,
x = yy = x + y
将 x
设置为 y
,然后将 y
设置为 x
(其中 == y
) 加上 y
,所以它等价于
x = yy = y + y
What is the difference between the following Python expressions:
# First:
x,y = y,x+y
# Second:
x = y
y = x+y
First gives different results than Second.
e.g.,
First:
>>> x = 1
>>> y = 2
>>> x,y = y,x+y
>>> x
2
>>> y
3
Second:
>>> x = 1
>>> y = 2
>>> x = y
>>> y = x+y
>>> x
2
>>> y
4
y is 3 in First and 4 in Second
In an assignment statement, the right-hand side is always evaluated fully before doing the actual setting of variables. So,
x, y = y, x + y
evaluates y
(let's call the result ham
), evaluates x + y
(call that spam
), then sets x
to ham
and y
to spam
. I.e., it's like
ham = y
spam = x + y
x = ham
y = spam
By contrast,
x = y
y = x + y
sets x
to y
, then sets y
to x
(which == y
) plus y
, so it's equivalent to
x = y
y = y + y
这篇关于Python 中的多重赋值和求值顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!