我试图弄清楚这些临时变量的含义

2024-10-02 16:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

def genfibon(n):      #fib sequence until n
   a=1
   b=1
   for i in range n:
      yield a
      t=a
      a=b
      b=t+b        

有人能解释t变量吗?它看起来像t=a所以a=b然后b=t因为a=ba=tb=t+b是怎么做的?你知道吗


Tags: infordefrangeuntilsequenceyieldfib
3条回答

假设a=2,b=3。你知道吗

t = a # now t = 2
a = b # now a = 3, but t is unchanged
b = t + b # now b = 5

关键是第二部分。t = a表示t获得与a相同的值。这并不意味着ta现在都是一回事。你知道吗

您可以在Python提示符中尝试:

a = 3
b = a
a = 5
print(b) # still 3

这叫做变量交换。如何替换变量的值?你知道吗

正如@smarx所说,当a = 2b = 3时,如何使之a = 3b = 2?你知道吗

当您执行a = 3时,a(2)的旧值丢失,因此您不知道用什么来设置b。所以我们把它存储在一个临时变量(t)中。你知道吗

所以

t = a //(saves 2 in t)
a = b //(now both a and b have same values)
b = t //(b gets the old value of a)
// now a = old value of b 
// and b = old value of a.

瞧,变量互换了。你知道吗

好吧,那就是交换。在本规范中仅部分使用。最后一条语句b = t + b代码所做的是,将a的旧值与b相加(而不是替换它)。为什么?将前面的2相加,得到斐波那契数列中的下一个数。你知道吗

2,3,5是斐波那契序列,因为5=2+3(给定2和3是种子值)。这正是这段代码要做的。你知道吗

在你的第一次跑步中

yield a # will return 1 
t = a  # which is 1
a = b  # which is 1
b = t + b  # which is 2 as t = 1 and b = 1 

在你的第二次跑步中

yield a # will return 1 
t = a  # which is 1
a = b  # which is 2
b = t + b  # which is 3 as t = 1 and b = 2

在你的第三次跑步中

yield a # will return 2 
t = a  # which is 2
a = b  # which is 3
b = t + b  # which is 5 as t = 2 and b = 3   

在你的第四次跑步中

yield a # will return 3 
t = a  # which is 3
a = b  # which is 5
b = t + b  # which is 8 as t = 3 and b = 5

等等。。。你知道吗

相关问题 更多 >