如何在Python中找到列表的平均值?

[1, 2, 3, 4]  ⟶  2.5

当前回答

简单的解决方案是avmedii -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

享受。

其他回答

print reduce(lambda x, y: x + y, l)/(len(l)*1.0)

或者像之前写的那样

sum(l)/(len(l)*1.0)

1.0是为了确保你得到一个浮点除法

在Udacity的问题中,我也有一个类似的问题要解决。而不是一个内置的函数,我编码:

def list_mean(n):

    summing = float(sum(n))
    count = float(len(n))
    if n == []:
        return False
    return float(summing/count)

比平时长得多,但对于初学者来说,这是相当具有挑战性的。

作为初学者,我只是编写了这个代码:

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

total = 0

def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total / len(numbers)

print average(L)
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)

你可以为平均值,使用率做一个函数:

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允许任意数量的答案。