Python:变量的用法及其差异("a,b = 0,1" VS"a = 0","b = 1") [英] Python: Usage of Variables and their difference ("a, b = 0, 1" VS "a = 0", "b = 1")
问题描述
我正在查看Python手册,并找到了斐波那契数生成器的以下代码段:
I was looking at the Python Manual and found this snippet for a Fibonacci-Number generator:
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
输出取决于n并返回有效的斐波那契数列.
The output is dependent on n and returns a valid Fibonacci sequence.
如果您将其重塑为像这样分别使用变量"a"和"b":
If you remodel this to use the variables "a" and "b" seperately like so:
def fib(n): # write Fibonacci series up to n
a = 0
b = 1
while b < n:
print(b, end=' ')
a = b
b = a+b
print()
然后它将打印一个以2的幂递增的数字序列(例如1、2、4、8、16等).
then it will print a number sequence that increments by the power of 2 (e.g. 1, 2, 4, 8, 16 and so on).
所以我想知道为什么会这样吗?两次使用变量之间的实际区别是什么?
So I was wondering why that happens? What is the actual difference between the two uses of variables?
推荐答案
操作:
a,b = b,a + b
等效于:
temp = a
a = b
b += temp
它使您可以同时进行两个计算,而无需中间/临时变量.
It lets you simultaneously do two calculations without the need of an intermediate/temporary variable.
区别在于,在第二段代码中,当您执行第二行 b = a + b
时,您已经在上一行中修改了 a
与第一段代码不同.
The difference is that in your second piece of code, when you do the second line b = a+b
, you have already modifed a
in the previous line which is not the same as the first piece of code.
>>> a = 2
>>> b = 3
>>> a,b
2 3
>>> a,b = b,a
>>> a,b
3 2
另一方面,如果您使用问题中显示的第二种方法:
On the other hand, if you use the second approach shown in your question:
>>> a = 2
>>> b = 3
>>> a,b
2 3
>>> a = b
>>> b = a
>>> a,b
3 3
这篇关于Python:变量的用法及其差异("a,b = 0,1" VS"a = 0","b = 1")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!