在 while 循环中增加列表索引

Increment list index in a while loop

我正在尝试打印斐波那契数列中的前 12 个数字。我的想法是增加两个列表索引号。

list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers

listint = list[0] #sets the list variable I want to incremented 
list2int = list[1] #set the other list variable to be incremented

while len(list) < 13:       #sets my loop to stop when it has 12 numbers in it
    x = listint + list2int       #calculates number at index 2
    list.append(x)     #appends new number to list
    listint += 1    #here is where it is supposed to be incrementing the index
    list2int +=1
print list

我的输出是:

[0, 1, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]

我要:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89

请注意我是初学者,我正在尝试在不使用内置函数的情况下执行此操作。 (我确定有某种斐波那契数列生成器)。

在此先感谢您的帮助!

问题出在 while 循环的最后两行。您每次都加 1 而不是使用列表的最后两个元素,即前面的斐波那契数:

list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers

listint = list[0] #sets the list variable I want to incremented 
list2int = list[1] #set the other list variable to be incremented

while len(list) < 13:       #sets my loop to stop when it has 12 numbers in it
    x = listint + list2int       #calculates number at index 2
    list.append(x)     #appends new number to list
    listint = list[-2]    #here is where it is supposed to be incrementing the index
    list2int = list[-1]
print list

更改 while 循环的第一行:

list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers

listint = list[0] #sets the list variable I want to incremented 
list2int = list[1] #set the other list variable to be incremented

while len(list) < 12:       #sets my loop to stop when it has 12 numbers in it
    x = list[listint] + list[list2int]       #calculates number at index 2
    list.append(x)     #appends new number to list
    listint += 1    #here is where it is supposed to be incrementing the index
    list2int +=1
print list

另外,要获得前 12 个数字,您可以将 while 循环条件设置为 < 12,因为 Python 列表索引从 0 开始。

list = [0,1]

while len(list) < 12:
    list.append(list[len(list)-1]+list[len(list)-2])
print list

性能不是很好,但又快又脏。 使用 < 12 因为在第 11 个循环中,您会将第 12 个条目添加到列表中。 使用 list[x] 您可以访问第 x 个条目,第一个条目从 0 开始。

编辑: 输出

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]