这两个代码有什么区别

时间:2019-02-11 16:31:28

标签: python python-3.x

我有2个不同的代码,我得到了不同的答案。我想知道有什么区别

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

第一个代码输出为:1 1 2 3 5 8 13 21 34

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

2 个答案:

答案 0 :(得分:6)

vessel_pln start_time start_lat start_lon end_time end_lat end_lon activity new_activity 1: AU89 2018-11-02 05:14:26 GMT 55.69713617 -5.65051533 2018-11-02 06:54:37 GMT 55.694627 -5.65454983 1 NO 2: AU89 2018-11-02 07:48:16 GMT 55.69693433 -5.65031783 2018-11-02 08:55:24 GMT 55.69539367 -5.6531755 2 NO 3: AU89 2018-11-02 09:03:28 GMT 55.6953905 -5.6531785 2018-11-02 09:44:00 GMT 55.69454683 -5.65567667 3 YES 4: AU89 2018-11-02 10:17:25 GMT 55.6904365 -5.6585925 2018-11-02 11:55:47 GMT 55.6937005 -5.65628133 4 NO 5: AU89 2018-11-05 06:39:12 GMT 55.69103567 -5.658306 2018-11-05 08:33:35 GMT 55.693022 -5.6531755 5 NO 使用x, y = y, x+yx的原始值在RHS上构造一个元组,然后对左侧的yx进行任何赋值。等同于

y

使用

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

您的新值x = y y = x + y y new 值(即x)添加到y;您已经失去了旧的价值。您需要改写

y

元组拆包是一种避免使用临时变量old_x = x x = y y = old_x + y 的方法。

答案 1 :(得分:2)

不同之处在于评估的顺序。

在第一个示例中,您有以下内容:

MacBook-Pro:test torn$ ls
file1   file2   file3   file4
MacBook-Pro:test torn$ cat *
this is file 1
this is file 2
this is file 3
this is file 4
MacBook-Pro:test torn$ tail -n +1 * > allFiles
MacBook-Pro:test torn$ cat allFiles 
==> file1 <==
this is file 1

==> file2 <==
this is file 2

==> file3 <==
this is file 3

==> file4 <==
this is file 4
MacBook-Pro:test torn$ 

这是在右侧评估两个表达式,然后将它们存储到元组中,然后在左侧解压缩它们。

因为这都是一个“主”表达式(元组)的一部分,所以在元组的构造过程中不会更新任何变量。这意味着:

x, y = y, x + y

一旦构造了元组,就同时设置了y, x+y evaluates as (old value of y), (old value of x) + (old value of y) x

第二个示例通过将赋值放入不同的语句中,使事情明显不同。这将导致在计算第二个赋值之前更改x的值:

y

这等效于:

x=y
y = x + y

x = (old value of y) y = (old value of y) + (new value of x == old value of y) 设置为y