python的 a,b=b,a+b 和 a=b b=a+b 的区别
def fab(max): n, a, b = 0, 0, 1 while n < max: print(b) a = b b = a + b n = n + 1 fab(10)
输出
1 1 2 4 8 16 32 64 128 256
而
def fab(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1 fab(10)
输出
1 1 2 3 5 8 13 21 34 55
我想这应该涉及到“=”赋值运算
a, b = b, a+b
先算“=”右边,b、a+b,然后赋值给a、b
应该分解为:
def fab(max): n, a, b = 0, 0, 1 while n < max: print(b) c = b b = a + b a = c n = n + 1 fab(10)
输出:
1 1 2 3 5 8 13 21 34 55
其他:
def fab(max): n, a, b = 0, 0, 1 while n < max: yield b c = b b = a + b a = c n = n + 1 for i in fab(10): print(i)
以前-好记性不如烂笔头
现在-好记性不如烂键盘