如何使用列表理解来创建斐波那契数列? [英] How can I create the fibonacci series using a list comprehension?
问题描述
我是python的新手,我想知道是否可以使用python的列表理解功能生成fibonacci系列.我不知道如何实现列表推导.我尝试了以下操作(目的是生成前五个斐波那契数):
I am new to python, and I was wondering if I could generate the fibonacci series using python's list comprehension feature. I don't know how list comprehensions are implemented. I tried the following (the intention was to generate the first five fibonacci numbers):
series=[]
series.append(1)
series.append(1)
series += [series[k-1]+series[k-2] for k in range(2,5)]
这段代码抛出错误: IndexError:列表索引超出范围
.
让我知道是否有可能使用列表理解来生成这样的系列.
Let me know if it is even possible to generate such a series using a list comprehension.
推荐答案
您不能那样做:首先对列表理解进行评估,然后对该列表进行评估已添加到系列
中.因此,基本上就像您写过一样:
You cannot do it like that: the list comprehension is evaluated first, and then that list is added to series
. So basically it would be like you would have written:
series=[]
series.append(1)
series.append(1)
temp = [series[k-1]+series[k-2] for k in range(2,5)]
series += temp
不过,您可以通过使用 list comprehension 作为强制副作用的一种方式来解决此问题,例如:
You can however solve this by using list comprehension as a way to force side effects, like for instance:
series=[]
series.append(1)
series.append(1)
[series.append(series[k-1]+series[k-2]) for k in range(2,5)]
请注意,我们在此处不要将结果添加到系列.仅使用列表推导,以便在 series
上调用 .append
.但是,有些人认为列表理解具有副作用,而更容易出错:它不是非常声明性的,并且如果不仔细地进行操作,往往会引入错误.
Note that we here do not add the result to series. The list comprehension is only used such that .append
is called on series
. However some consider list comprehensions with side effects rather error prone: it is not very declarative and tends to introduce bugs if not done carefully.
这篇关于如何使用列表理解来创建斐波那契数列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!