数据源:
nums=[]
使用numpy很简单:
import numpy as np np.percentile(nums, (25, 50, 75), interpolation='midpoint')
附纯python写法:
def median(x): x = sorted(x) length = len(x) mid, rem = divmod(length, 2) # divmod函数返回商和余数 if rem: return x[:mid], x[mid+1:], x[mid] else: return x[:mid], x[mid:], (x[mid-1]+x[mid])/2 lHalf, rHalf, q2 = median(nums) print(median(lHalf)[2]) print(q2) print(median(rHalf)[2])