寻找列表的平均值

673

如何在Python中计算列表的平均值?

[1, 2, 3, 4]  ⟶  2.5

59
如果您有安装numpy的能力,可以使用numpy.mean函数。 - mitch
9
sum(L) / float(len(L)) 的意思是计算列表 L 的平均值。在调用代码中处理空列表,可以使用 if not L: ... 来判断。 - n611x007
抱歉,我无法翻译此内容,因为它是一个链接。请提供要翻译的具体文本。 - n611x007
6
@mitch: 这不是你是否负担得起安装numpy的问题。numpy本身就是一个完整的工具。重点是你是否真正需要numpy。为了计算平均值而安装一个16mb的C扩展程序numpy,对于那些没有在其他方面使用它的人来说,这将是非常不切实际的。 - n611x007
4
如果使用Python 3,为了计算平均值而不必安装整个NumPy包,我们可以使用统计模块完成此操作,只需使用"from statistic import mean"即可。如果使用Python 2.7或更低版本,则可以从以下源代码安装统计模块:https://hg.python.org/cpython/file/default/Lib/statistics.py 文档链接:https://docs.python.org/dev/library/statistics.html。 - 25mhz
25个回答

0

我想再添加另一种方法

import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)

0
结合以上几个答案,我得出了以下使用reduce的解决方案,并且不假设你在缩减函数内部有可用的L
from operator import truediv

L = [15, 18, 2, 36, 12, 78, 5, 6, 9]

def sum_and_count(x, y):
    try:
        return (x[0] + y, x[1] + 1)
    except TypeError:
        return (x + y, 2)

truediv(*reduce(sum_and_count, L))

# prints 
20.11111111111111

0
你可以为平均值创建一个函数,用法:
average(21,343,2983) # You can pass as many arguments as you want.

这里是代码:

def average(*args):
    total = 0
    for num in args:
        total+=num
    return total/len(args)

*args 允许传递任意数量的参数。


使用方法为:average(3,5,123),但您可以输入其他数字。请记住它返回一个值,而不是打印任何东西。 - Python

0

简单的解决方案是使用avemedi-lib库。

pip install avemedi_lib

将其包含到您的脚本中

from avemedi_lib.functions import average, get_median, get_median_custom


test_even_array = [12, 32, 23, 43, 14, 44, 123, 15]
test_odd_array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Getting average value of list items
print(average(test_even_array))  # 38.25

# Getting median value for ordered or unordered numbers list
print(get_median(test_even_array))  # 27.5
print(get_median(test_odd_array))  # 27.5

# You can use your own sorted and your count functions
a = sorted(test_even_array)
n = len(a)

print(get_median_custom(a, n))  # 27.5

享受。


-5
numbers = [0,1,2,3]

numbers[0] = input("Please enter a number")

numbers[1] = input("Please enter a second number")

numbers[2] = input("Please enter a third number")

numbers[3] = input("Please enter a fourth number")

print (numbers)

print ("Finding the Avarage")

avarage = int(numbers[0]) + int(numbers[1]) + int(numbers[2]) + int(numbers [3]) / 4

print (avarage)

1
如果用户向您的数组中添加浮点数,结果将非常不精确。 - Flame_Phoenix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接