如何用python求一组数据的平均数、标准差和中位数,并保留两位小数?
numbers=eval(input("请输入数据,并以逗号分隔:"))
sum=0
count=0
for i in numbers:
sum=sum+i
a=sum/len(numbers)
print(f"平均值:{a:.2f}")
接下来如何写?
如何用python求一组数据的平均数、标准差和中位数,并保留两位小数?
numbers=eval(input("请输入数据,并以逗号分隔:"))
sum=0
count=0
for i in numbers:
sum=sum+i
a=sum/len(numbers)
print(f"平均值:{a:.2f}")
接下来如何写?
def mean(numbers): #计算平均值
s=0.0
for n in numbers:
num=int(n)
s=s+num
return s/len(numbers)
def dev(numbers,mean): #计算标准差
sdev=0
for num in numbers:
sdev=sdev+(num-mean)**2
return pow(sdev/(len(numbers)-1),0.5)
def median(numbers): #计算中位数
news_numbers=sorted(numbers)
size=len(news_numbers)
if size%2==0:
med=(news_numbers[size//2-1]+news_numbers[size//2])/2
else:
med=news_numbers[size//2]
return med
numbers=eval(input("请输入数据,并以逗号分隔:"))
print("平均值:%.2f,标准差:%.2f,中位数:%.2f"%(mean(numbers),dev(numbers,mean(numbers)),median(numbers)))