Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
这2是从哪里来的?使用python列表的斐波那契数列_Python_Python 3.x_List_While Loop_Fibonacci - Fatal编程技术网

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

这2是从哪里来的?使用python列表的斐波那契数列,python,python-3.x,list,while-loop,fibonacci,Python,Python 3.x,List,While Loop,Fibonacci,如果您不想阅读本文,我已经在Youtube视频中解释了这个问题: 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 下面是我使用python生成Fibonacci序列的

如果您不想阅读本文,我已经在Youtube视频中解释了这个问题:

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
下面是我使用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循环进行的。 如果您干运行代码,您将看到代码输出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之间的实际差异。

当列表1变为
[0,1,1]
时,列表1的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个;0,1,1,2,3,5,8,13,21,34,55…哦,我的上帝。非常感谢:)