1 #CalStatisticsV1.py 2 def getNum(): #获取用户不定长度的输入 3 nums=[] 4 test=input("请输入要存储的数据(回车退出):") 5 while test != "": 6 nums.append(eval(test)) 7 test=input("请继续输入其他数据(结束回车退出):") 8 9 return nums 10 11 def mean(means_n): #求平均值 12 s=0 13 mean_result=0 14 for i in means_n: 15 s=s+i 16 mean_result=s/len(means_n) 17 return mean_result 18 19 def median(numbers): #求中位数 20 tem_s=sorted(numbers) #临时排序 21 size=len(numbers) 22 23 if size%2==0: 24 med=(tem_s[size//2-1]+tem_s[size//2])/2 25 else: 26 med=(tem_s[size//2]) 27 print(tem_s) #打印排序后的列表 28 return med 29 30 def dev(numbers,mean): #计算方差 31 sdev=0 32 for num in numbers: 33 sdev=sdev+pow(num-mean,2) 34 var=pow(sdev/len(numbers),0.5) 35 return var 36 37 38 n=getNum() 39 means=mean(n) 40 medians=median(n) 41 var=dev(n,means) 42 print("列表:{},平均值:{:.2f},中位数:{:.2f},方差:{}".format(n,means,medians,var))