Python中的多个分配和评估顺序 [英] Multiple assignment and evaluation order in Python

查看:90
本文介绍了Python中的多个分配和评估顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Python表达式之间有什么区别?

What is the difference between the following Python expressions:

# First:

x,y = y,x+y

# Second:

x = y
y = x+y

第一给出的结果与第二不同.

例如

第一:

>>> x = 1
>>> y = 2
>>> x,y = y,x+y
>>> x
2
>>> y
3

第二:

>>> x = 1
>>> y = 2
>>> x = y
>>> y = x+y
>>> x
2
>>> y
4

y First 中为3,在 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

评估y(我们称结果ham),评估x + y(称spam),然后x设置为ham,将y设置为spam.也就是说,就像

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

通过对比,

x = y
y = x + y

x设置为y,然后将y设置为x(其中== y)加上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中的多个分配和评估顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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