【问题标题】:Calculate the average of lists in Python [duplicate]计算Python中列表的平均值[重复]
【发布时间】:2020-01-25 12:55:32
【问题描述】:

我想计算列表中列表中项目的平均值(平均值)。结果应该是一个元组列表:

Input_1 = [[2,4,6], [4,8,1]]            # ==> [(4,), (4.333,)]
Input_2 = [2,6], [8,6], [1,5], [4,5,1]  # ==> [(4,), (7,), (3,), (3.333,)]

【问题讨论】:

  • [2, 4, 6]6 的平均值如何?
  • 这个问题没有显示任何解决这个问题的努力。
  • @HenryHarutyunyan 我输出错误,已更正

标签: python python-3.x list for-loop tuples


【解决方案1】:

这是一个使用列表推导的简单解决方案

from statistics import mean

Output_1 = [(mean(l),) for l in Input_1]

如果您不想使用 statistics 库,您可以做的另一件事是

Output_1 = [(sum(l)/len(l),) for l in Input_1]

【讨论】:

    【解决方案2】:

    下面是一个简单的方法来完成这个任务

    # importing mean() 
    from statistics import mean 
    
    def Average(Input):
        Output =[]                   # Initialising a blank Output List
        for x in Input:
            a = round(mean(x),3)     # Rounding the mean value to 3 decimal digits
            t= (a,)                  # Making tuple with Mean
            Output.append(t)         # Making the list of Mean tuples
        return Output
    
    Input_1=[[2,4,6],[4,8,1]]
    Input_2=[2,6],[8,6],[1,5],[4,5,1]
    print(Average(Input_1))
    print(Average(Input_2))
    

    【讨论】:

      【解决方案3】:

      您可以使用高阶函数map(Python 从 LISP 继承它)将函数应用于可迭代对象(例如列表)的所有成员:

      from statistics import mean
      
      Input_1 = [[2,4,6], [4,8,1]]
      Input_2 = [2,6], [8,6], [1,5], [4,5,1]
      
      def mean_in_tuple(it):
          return (mean(it), )
      
      for it in [Input_1, Input_2]:
          result = list(map(mean_in_tuple, it))
          print(result)
      

      乍一看,它与列表理解没有什么不同。但它可能导致一种完全不同的编码风格,称为函数式编程。这种风格通常更容易推理和测试。它还可以很好地组合成管道:

      map(format_euro, map(dollar_to_euro, map(mean_in_tuple, input)))
      

      【讨论】:

      • 不过,列表推导式在 Python 中通常是首选。 result = [mean_in_tuple(mean(x)) for x in [Input_1, Input_2]].
      • 我知道。但是在学习了 LISP 和 Haskell 之后,这种“命令式”的编程风格对我来说感觉很奇怪,这就是为什么我想添加一个替代方案。用其他编程风格引起人们的兴趣从来没有什么坏处。 :)
      猜你喜欢
      • 2021-03-18
      • 2015-11-02
      • 2016-05-22
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2018-05-16
      相关资源
      最近更新 更多