我有一个可以打印斐波那契数列的功能
def fib(n):
""" print the fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a)
a, b = b, a + b
效果很好。但是,当我更改某些编码样式时,它无法按我的预期工作。那么这是怎么回事?
def fib(n):
""" print the fibonacci series up to n."""
a = 0
b = 1
while a < n:
print(a)
a = b
b = a + b
上面的代码不会输出与第一个代码相同的结果,但是我可以在两个函数中看到相同的代码。我是python的初学者。
答案 0 :(得分:3)
是的,有不同的行为。 =
右侧的所有内容都会在赋值之前被评估 到=
的左侧。多重分配只是意味着您在右侧计算一个元组,然后在左侧将其分配给一个元组。
a, b = b, a+b
# computes (b, a+b)
# matches with (a, b)
# assigns the computed values to a and b respectively
与
a = b
# assigns the value of b to a
b = a + b
# computes a + b (since a was just set equal to b, this is the same as b + b)
# assigns that computed value to b
如果您需要将所有分配都放在单独的行上,那么您将需要一个临时持有变量来交换a
和b
:
temp = a
a = b
b = b + temp
或采取一些措施来保留b
和a
之间的差异:
b = b + a
a = b - a
多次分配是解决该问题的“最正确”方法,主要是因为它最简洁。
答案 1 :(得分:0)
好吧,您没有正确交换第二种方法中的值
直接解决方案是:
def fib(n):
a = 0
b = 1
while a < n:
print(a)
c = a + b # c is the temporary variable
a = b
b = c
在第一种方法中,首先对加法进行求值,然后 a变为b,b成为附加值。在第二种方法中,您将添加的值存储在其他变量中,然后按照上面的代码进行交换值。