Python:使用列表推导生成几何级数 [英] Python: Generate a geometric progression using list comprehension

查看:104
本文介绍了Python:使用列表推导生成几何级数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,是否可以仅使用列表推导来生成几何级数?我不知道如何引用添加到列表中的元素.

In Python, Can I generate a geometric progression using list comprehensions alone? I don't get how to refer to elements that were added to the list.

那就像编写python代码以计算几何级数生成列表-几何级数.

推荐答案

列表推导不允许您引用以前的值.您可以使用更合适的工具:

List comprehensions don't let you refer to previous values. You could get around this by using a 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)]

这篇关于Python:使用列表推导生成几何级数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆