【问题标题】:Find the cumulative average of the list [8,1,4,2,1] using accumulate() and lambda function in python在python中使用accumulate()和lambda函数求列表[8,1,4,2,1]的累积平均值
【发布时间】:2021-10-22 06:53:59
【问题描述】:

嗨,我是 python 新手,我想使用累积()和 lambda 函数找到给定列表的累积平均值,我已经编写了代码,直到累积(),但我无法使用 lambda 函数找到累积平均值。谁能帮帮我?

enter code here
a= [8,1,4,2,6]
import itertools as it
l=[]
l = it.accumulate(a)
print(list(l))


My output should be like this [4.5,4.33,3.75,4.2]

【问题讨论】:

    标签: python-3.x list lambda accumulate


    【解决方案1】:

    使用累积肯定不是计算累积平均值的最简单/最简洁的方法。但你可以这样做是为了好玩。您必须在 enumerate(a) 上应用它,因为 lambda 函数不知道其参数在列表中的位置:

    a= [8,1,4,2,6]
    import itertools as it
    l=[]
    l = it.accumulate(list(enumerate(a)), lambda x,y: (y[0], (x[1]*(x[0]+1) + y[1])/(y[0]+1)))
    print(list(map(lambda x: x[1], l)))
    

    【讨论】:

      【解决方案2】:
      from  itertools import accumulate
      result=accumulate([8,1,4,2,6],lambda x,y:(x+y)/2)
      for res in result :
          print(res)
      

      【讨论】:

      • 8 4.5 4.25 3.125 4.5625
      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2022-01-04
      • 2016-07-11
      • 1970-01-01
      • 2011-12-15
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多