简体   繁体   English

这2个代码有什么区别

[英]What's the difference between this 2 code

I have 2 code which is a different and I get different answers.我有 2 个不同的代码,我得到了不同的答案。 I wonder what the difference is我想知道有什么区别

x, y = 0, 1

while y < 50:
    print(y)
    x, y = y, x + y

x=0
y=1

while y < 50:
    print(y)
    x=y
    y=x+y

first code output is: 1 1 2 3 5 8 13 21 34第一个代码输出是:1 1 2 3 5 8 13 21 34

and two code: 1 2 4 8 16 32和两个代码:1 2 4 8 16 32

x, y = y, x+y constructs an tuple on the RHS using the original values of x and y before performing any assignments to x and y on the left. x, y = y, x+y的构建体的使用的原始值在RHS元组xy执行任何任务之前xy在左侧。 It's equivalent to它相当于

new_y = y
new_x = x + y
x = new_x
y = new_y

With

x = y
y = x + y

your new value of y is adding the new value of x ( which is y ) to y ; y值是将x值(即y )添加到y you've already lost the old value.你已经失去了旧的价值。 You would need to write instead你需要写

old_x = x
x = y
y = old_x + y

The tuple unpacking is a way to avoid the need for the temporary variable old_x .元组解包是一种避免需要临时变量old_x

The difference is the order of evaluation.区别在于评估的顺序。

In the first example, you have this:在第一个例子中,你有这个:

x, y = y, x + y

This is evaluating two expressions on the right hand side, and then storing them into a tuple, then unpacking them on the left hand side.这是在右侧计算两个表达式,然后将它们存储到一个元组中,然后在左侧将它们解包。

Because this is all part of one "master" expression (the tuple), no variables are updated during the construction of the tuple.因为这是一个“主”表达式(元组)的一部分,所以在元组的构造过程中不会更新任何变量。 This means:这意味着:

y, x+y evaluates as (old value of y), (old value of x) + (old value of y)

Once the tuple has been constructed, both x and y are set.一旦构造了元组,就设置了xy

Your second example makes things explicitly different by putting the assignments into different statements.您的第二个示例通过将赋值放入不同的语句中使事情明显不同。 This causes the value of x to be changed before the computation of the second assignment:这会导致在计算第二个赋值之前更改 x 的值:

x=y
y = x + y

This is equivalent to:这相当于:

x = (old value of y)
y = (old value of y) + (new value of x == old value of y)

Which sets y to 2 * y .这将y设置为2 * y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM