gpt4 book ai didi

python - python 中的单个 var 赋值和多个 var 赋值之间有什么不同的行为吗?

转载 作者:太空宇宙 更新时间:2023-11-04 11:06:48 25 4
gpt4 key购买 nike

我有一个打印斐波那契数列的函数

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 初学者。

最佳答案

是的,有不同的行为。 = 右侧的所有内容都在被赋值= 左侧之前进行评估。多重赋值只是意味着您在右侧计算一个元组,并将其分配给左侧的一个元组。

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

如果您需要在不同的行上进行所有分配,那么您将需要一个临时变量来交换 ab:

temp = a
a = b
b = b + temp

或者做一些奇特的事情来保留 ba 之间的区别:

b = b + a
a = b - a

多重赋值是解决问题“最正确”的方法,主要是因为它最简洁。

关于python - python 中的单个 var 赋值和多个 var 赋值之间有什么不同的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59261037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com