Python 中的多重赋值和求值顺序 [英] Multiple assignment and evaluation order in Python

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

问题描述

以下 Python 表达式有什么区别:

# 首先:x,y = y,x+y# 第二:x = yy = x+y

FirstSecond 给出的结果不同.

例如

首先:

<预><代码>>>>x = 1>>>y = 2>>>x,y = y,x+y>>>X2>>>是3

第二:

<预><代码>>>>x = 1>>>y = 2>>>x = y>>>y = x+y>>>X2>>>是4

yFirst 中是 3,在 Second

中是 4

解决方案

在赋值语句中,总是在实际设置变量之前对右侧进行全面评估.所以,

x, y = y, x + y

评估y(我们称结果为ham),评估x + y(称其为spam), thenx 设置为 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 中的多重赋值和求值顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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