我是python编程的新手,我正在尝试基于生成器编写fib。我试过这个:
def fib(n):
a = 0
b = 1
for _ in range(n):
yield a
print(a)
a, b = b, a + b
print((a,b))
和这一个:
def fib(n):
a = 0
b = 1
for _ in range(n):
yield a
a = b
b = a + b
print(list(fib(a)))
结果不同,为什么会发生这种情况?
答案 0 :(得分:1)
Python不会破坏这个
a, b = b, a + b
进入这个:
a = b
b = a + b
相反,Python编译器首先通过转换它来评估表达式的右手:
a = 0
b = 1
a, b = b, a + b
进入这个:
a = 0
b = 1
a, b = 1, 1
然后按正确顺序分配。
因此a
和b
变为1。
答案 1 :(得分:0)
一步一步找出来!
a = 0
b = 1
# loop starts: # loop starts
yield a # yields 0, a=0, b=1 yield a # yields 0, a=0, b=1
a = b # a=1, b=1 a, b = b, b+a # a=1, b=1
b = a + b # a=1, b=2
# loop
yield a # yields 1, a=1, b=2 yield a # yields 1, a=1, b=1
a = b # a=2, b=2 a, b = b, b+a # a=1, b=2
b = a + b # a=2, b=4
# loop
yield a # yields 2 a=2, b=4 yield a # yields 1, a=1, b=2
a = b # a=4, b=4 a, b = b, b+a # a=2, b=3
b = a + b # a=4, b=8
# etc...