在Python中,我可以使用列表解析单独生成几何级数吗?我不知道如何引用添加到列表中的元素。Python:使用列表理解生成几何级数
这就像Writing python code to calculate a Geometric progression或Generate list - geometric progression。
在Python中,我可以使用列表解析单独生成几何级数吗?我不知道如何引用添加到列表中的元素。Python:使用列表理解生成几何级数
这就像Writing python code to calculate a Geometric progression或Generate list - geometric progression。
列表解析不会让您引用先前的值。你可以解决这个问题通过使用more appropriate tool:
from itertools import accumulate
from operator import mul
length = 10
ratio = 2
progression = list(accumulate([ratio]*length, mul))
,或者避免使用以前的值:如果一个几何级数由a_n = a * r ** (n - 1)
和a_n = r * a_(n - 1)
定义
progression = [start * ratio**i for i in range(n)]
,那么你可以只是做如下:
a = 2
r = 5
length = 10
geometric = [a * r ** (n - 1) for n in range(1, length + 1)]
print(geometric)
# [2, 10, 50, 250, 1250, 6250, 31250, 156250, 781250, 3906250]