【发布时间】:2016-11-09 04:52:16
【问题描述】:
在 Python 中,我可以单独使用列表推导生成几何级数吗?我不知道如何引用添加到列表中的元素。
就像Writing python code to calculate a Geometric progression 或Generate list - geometric progression。
【问题讨论】:
标签: python list python-3.x list-comprehension
在 Python 中,我可以单独使用列表推导生成几何级数吗?我不知道如何引用添加到列表中的元素。
就像Writing python code to calculate a Geometric progression 或Generate list - geometric progression。
【问题讨论】:
标签: python list python-3.x list-comprehension
列表推导不允许您引用以前的值。您可以使用more appropriate tool 来解决这个问题:
from itertools import accumulate
from operator import mul
length = 10
ratio = 2
progression = list(accumulate([ratio]*length, mul))
或避免使用以前的值:
progression = [start * ratio**i for i in range(n)]
【讨论】:
如果几何级数由a_n = a * r ** (n - 1) 和a_n = r * a_(n - 1) 定义,那么您只需执行以下操作:
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]
【讨论】: