Python基础——基本统计值计算

计算键入数据的平均值、方差和中位数

#基本统计值计算
def getNum():   #键盘输入需要统计的数据
    nums = []
    iNumStr = input("请输入数字(回车退出):")
    while iNumStr !="":
        nums.append(eval(iNumStr))
        iNumStr = input("请输入数字(回车退出):")
    return nums

def mean(numbers):  #计算平均值
    s= 0.0
    for num in numbers:
        s = 0.0
        for num in numbers:
            s = s + num
        return s / len(numbers)

def dev(numbers, mean):
    sdev = 0.0
    for num in numbers:
        sdev = sdev + (num - mean)**2
    return pow(sdev / (len(numbers)-1),0.5)

def median(numbers):
    sorted(numbers)
    size = len(numbers)
    if size % 2 == 0:
        med = (numbers[size//2-1] + numbers[size//2])/2
    else:
        med = numbers[size//2]  #   //为整除
    return med

n = getNum()
m = mean(n)
print("平均值:{},方差:{:.2},中位数:{}。".format(m,dev(n,m),median(n)))

结果如下:
Python基础——基本统计值计算_第1张图片

你可能感兴趣的:(Python,python,机器学习)