如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
当前回答
对于Python 3.4+,使用新的统计模块中的mean()来计算平均值:
from statistics import mean
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
mean(xs)
其他回答
简单的解决方案是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
享受。
如果你想要的不仅仅是平均值(又名平均),你可以看看scipy的统计:
from scipy import stats
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(stats.describe(l))
# DescribeResult(nobs=9, minmax=(2, 78), mean=20.11111111111111,
# variance=572.3611111111111, skewness=1.7791785448425341,
# kurtosis=1.9422716419666397)
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)
在Udacity的问题中,我也有一个类似的问题要解决。而不是一个内置的函数,我编码:
def list_mean(n):
summing = float(sum(n))
count = float(len(n))
if n == []:
return False
return float(summing/count)
比平时长得多,但对于初学者来说,这是相当具有挑战性的。
在列表中求平均值 通过使用以下PYTHON代码:
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(sum(l)//len(l))
试着简单一点。