计算Python中列表的平均值

2024-03-29 08:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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,)]

Tags: 项目列表input平均值元组
3条回答

下面是一个使用列表理解的简单解决方案

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]

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

# 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))

您可以使用高阶函数map(Python继承自LISP),它将函数应用于iterable(如列表)的所有成员:

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)))

相关问题 更多 >