Python四分位和中位数计算代码

Python四分位和中位数计算代码- https://www.cnblogs.com/iAmSoScArEd/p/14832474.html -我超怕的

 

############
# Name:计算四分位和中位数
# Author:我超怕的
# Date:2021-05-21
###########

# 接受、处理数据
numbers=[1,2,3,4,5,6,7]
numbers.sort()
#print(numbers)
# 总个数
total = len(numbers)

# 四分位位置
local = []
for i in range(5):
    n = (i*(total-1)/4)+1
    local.append(n)

# print(local)

# 四分位计算
# 整数部分
numbersInteger = []
for i in local:
    numbersInteger.append(int(i))

# 整数结果
numbersIntergerResults = []
for i in numbersInteger:
    #print(i-1)
    numbersIntergerResults.append(numbers[i-1])

#print(numbersIntergerResults)
# 整数四分位下一个数
numbersIntergerNextResults = []
for i in numbersInteger:
    if i>= total:
        i =total-1
    numbersIntergerNextResults.append(numbers[i])

# 差值
numbersIntergerSubResults = []
for i in range(5):
    numbersIntergerSubResults.append(numbersIntergerNextResults[i]-numbersIntergerResults[i])


# 小数部分
numbersFloat = []
for i in local:
    numbersFloat.append('0.'+str(i).split('.')[1])


# 四分位结果计算
results = []
numbersFloatResults = []
for i in range(5):
    results.append(float(numbersFloat[i])*numbersIntergerSubResults[i]+numbersIntergerResults[i])

splitStr = '----------------------------------------'
print('原数据:{}'.format(numbers))
print('{}\n四分位对应:0%, 25%, 50%, 75%, 100%\n四分位数:{}\n{}'.format(splitStr,results,splitStr))

if total%2 == 0:
    print('中位数:{}'.format((numbers[int(total/2)-2]+numbers[int(total/2)-1]/2)))
else:
    print('中位数:{}'.format(numbers[int((total-1)/2)]))

 

posted @ 2021-05-21 17:44  我超怕的  阅读(1863)  评论(0编辑  收藏  举报