这 2 从哪里输出?使用 python 列表的斐波那契数列

From where this 2 came in output? Fibonacci series using python Lists

如果你不想看这篇文章,我已经在这个 Youtube 视频中解释了这个问题: https://youtu.be/Ekkkgjf0F_s

以下是我使用 python 生成 Fibonacci 系列的代码 列出。

list1 = [0, 1]
x=1
while x <=2:
    length = len(list1)
    first =list1[length-2]
    second =list1[length-1]
    third = first + second
    list1.append(third)
    x+=1
    print list1

当 while 循环 运行 进行第一次迭代时,它会按顺序生成即将到来的元素,并在列表中准确存储它应该执行的操作。 该列表现在将变为:

list1 = [0,1,1]

但令我困惑的是,第二次迭代是由 while 循环进行的。 如果你把代码干运行,你会看到代码输出的是2(根据斐波那契数列,是对的) 但是如果我们干燥运行代码,第4个元素应该是3而不是2

第二次交互,长度​​=3>>干运行以下:

 3-2=1
    3-1=2
    1+2=3
    list1 should be: [0,1,1,3]

但我得到的输出是: list1=[0,1,1,2]

我不明白,这 2 是怎么输出的。

您的列表有 len() 个 3,因此您的算法将元素 1 和 2(均为 1)相加。这就是为什么您会返回 2.

编辑:这正是斐波那契数列的走向....

代码注释如下:

length = len(list1)       #3
first =list1[length-2]    #list on index 1 is value 1
second =list1[length-1]   #list on index 2 is value 1
third = first + second    # 1+1 = 2
list1.append(third)       # 2 is appended
x+=1
print list1

您可能将列表索引 [1] 上的值与列表 3 和 1 的 len 之间的实际差异混淆了。

当你的list1变为[0,1,1]时,list1的len为3.

现在尝试运行以下操作:

length = len(list1) = 3
first = list1[length-2] = list1[3-2] = list1[1] = 1
second = list1[length-1] = list1[3-1] = list1[2] = 1
third = first + second = 1 + 1 = 2

因此,它将 2 添加到列表中。