难以理解分配变量的 python 语法
Trouble understanding python syntax for assigning variables
我正在查看来自 python
的斐波那契数列程序
#!/usr/bin/python3
# simple fibonacci series
# the sum of two elements defines the next set
a, b = 0, 1
while b < 50:
print(b)
a, b = b, a + b
print("Done")
结果输出如下所示:1, 1, 2 ,3 ,5 ,8 ,13 ,21, 34, Done
我对 a, b = b, a + b
的语法有点困惑
扩展更多的等效版本是什么?
编辑答案
好的,在阅读了一些东西之后,下面是一个等效的方法,用一个 c
临时占位符来获取原始 a
#!/usr/bin/python3
# simple fibonacci series
# the sum of two elements defines the next set
a = 0
b = 1
c = 0
while b < 50:
print(b)
c = a
a = b
b = a + c
print("Done")
此处有更多方法:Is there a standardized method to swap two variables in Python?,包括元组、异或和临时变量(如此处)
a, b = b, a + b
相当于
a = b; b = a + b
除了这会在分配给 b
时使用 a
的新值,而不是预期的原始值。
我正在查看来自 python
的斐波那契数列程序#!/usr/bin/python3
# simple fibonacci series
# the sum of two elements defines the next set
a, b = 0, 1
while b < 50:
print(b)
a, b = b, a + b
print("Done")
结果输出如下所示:1, 1, 2 ,3 ,5 ,8 ,13 ,21, 34, Done
我对 a, b = b, a + b
扩展更多的等效版本是什么?
编辑答案
好的,在阅读了一些东西之后,下面是一个等效的方法,用一个 c
临时占位符来获取原始 a
#!/usr/bin/python3
# simple fibonacci series
# the sum of two elements defines the next set
a = 0
b = 1
c = 0
while b < 50:
print(b)
c = a
a = b
b = a + c
print("Done")
此处有更多方法:Is there a standardized method to swap two variables in Python?,包括元组、异或和临时变量(如此处)
a, b = b, a + b
相当于
a = b; b = a + b
除了这会在分配给 b
时使用 a
的新值,而不是预期的原始值。