python基本统计方法

基本统计方法

通过用户输入一组数据(用户一个一个输入),然后计算数据的中位数/平均值/方差/求和

nums = []

while True:
    num1 = input('请输入你需要输入的数字(输入 q 退出):')
    if num1 == 'q':
        break
    nums.append(int(num1))

求和

def get_sum(nums): 
    count = 0
    for i in nums:
        count += int(i)

    return count

count = get_sum(nums)
print('count:',count)

平均数

def get_average(nums):
    count = get_sum(nums)
    average_count = count/len(nums)

    return average_count

average_count = get_average(nums)
print(average_count)

方差

def get_variance(nums):
    average_count = get_average(nums)

    variance_count = 0
    for i in nums:
        variance_count += pow(i-average_count,2)

    return variance_count

variance_count = get_variance(nums)
print(variance_count)

中位数

def get_median(nums):  # ['123', '32', '123', '234']
    #                     0      1      2    3
    nums.sort()

    nums_len = len(nums)
    if nums_len % 2 == 0:
        print((nums[int(nums_len / 2 - 1)] + nums[int(nums_len / 2)]) / 2)
    else:                          
        print(nums[nums_len // 2])


get_median(nums)

posted @ 2019-07-18 14:46  豆瓣酱瓣豆  阅读(740)  评论(0编辑  收藏  举报