【问题标题】:Python: Generate a geometric progression using list comprehensionPython:使用列表推导生成几何级数
【发布时间】:2016-11-09 04:52:16
【问题描述】:

在 Python 中,我可以单独使用列表推导生成几何级数吗?我不知道如何引用添加到列表中的元素。

就像Writing python code to calculate a Geometric progressionGenerate list - geometric progression

【问题讨论】:

    标签: python list python-3.x list-comprehension


    【解决方案1】:

    列表推导不允许您引用以前的值。您可以使用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)]
    

    【讨论】:

      【解决方案2】:

      如果几何级数由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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-14
        • 1970-01-01
        • 2018-08-22
        • 2011-08-14
        • 2011-07-27
        相关资源
        最近更新 更多