python 问题 如何用python 求n个数的平均值 然后保留小数
# coding = GBK
a =[1,2,3,4,5]
sum=0
b = len(a)
print("这个数组的长度为:",b)
for i in a:
sum =sum +i
print("这个数组之和为:",sum)
print("这个数组平均数为",sum/b)
或
import sys
sum = 0
cnt = 0
f = open('1.txt', 'r')
files = f.readline()
while (files ):
sum = sum + float(files .split(",")[0])
cnt = cnt + 1
files = f.readline()
print(sum / cnt)
f.close()
或者。
#!/usr/bin/env pythonimport timeimport numpy as np
dd = np.random.randint(0, 20, size=(2*1000*1000))t_start = time.clock()avg_sum1 =
0.0BlockOffset = 0 while BlockOffset < len(dd):
if dd[BlockOffset + 1] <= 10:
avg_sum1 += dd[BlockOffset + 1] * 0.1
else:
avg_sum1 += dd[BlockOffset + 0] * 0.01
BlockOffset += 2print('Avg: ' + str(avg_sum1 / len(dd) / 2)) print('Exe time: ' +
str(time.clock() - t_start))
扩展资料:
python 实现求和、计数、最大最小值、平均值、中位数、标准偏差、百分比。
import sys
class Stats:
def __init__(self, sequence):
# sequence of numbers we will process
# convert all items to floats for numerical processing
self.sequence = [float(item) for item in sequence]
def sum(self):
if len(self.sequence) < 1:
return None
else:
return sum(self.sequence)
def count(self):
return len(self.sequence)
def min(self):
if len(self.sequence) < 1:
return None
else:
return min(self.sequence)
def max(self):
if len(self.sequence) < 1:
return None
else:
return max(self.sequence)
def avg(self):
if len(self.sequence) < 1:
return None
else:
return sum(self.sequence) / len(self.sequence)
def median(self):
if len(self.sequence) < 1:
return None
else:
self.sequence.sort()
return self.sequence[len(self.sequence) // 2]
def stdev(self):
if len(self.sequence) < 1:
return None
else:
avg = self.avg()
sdsq = sum([(i - avg) ** 2 for i in self.sequence])
stdev = (sdsq / (len(self.sequence) - 1)) ** .5
return stdev
def percentile(self, percentile):
if len(self.sequence) < 1:
value = None
elif (percentile >= 100):
sys.stderr.write('ERROR: percentile must be < 100. you supplied: %s\n'% percentile)
value = None
else:
element_idx = int(len(self.sequence) * (percentile / 100.0))
self.sequence.sort()
value = self.sequence[element_idx]
return value
推荐于2017-06-27
round函数用来确定小数位数
如果你只想要小数部分: sum(n1,n2,n3,...,nn)/n-sum(n1,n2,n3,...,nn)//n
//为整除符号
1.如果你是要返回一定位小数的结果:
>>> def average(bits,*args):
from numbers import Number
for arg in args:
if not isinstance(arg,Number):
raise TypeError('你传入了非数字的参数')
return round(sum(args)/len(args),bits)
>>> average(5,1,2,3,8,3,2)
3.16667
>>>
2.如果要只保留小数部分:
>>> def average(*args):
from numbers import Number
for arg in args:
if not isinstance(arg,Number):
raise TypeError('你传入了非数字的参数')
s,Len=sum(args),len(args)
return s/Len-s//Len
>>> average(1,2,3,8,3,2)
0.16666666666666652
>>>
>>> l=[1, 2, 3, 4, 5, 4,3,2,1] #输入数字到数组中
>>> sum(l)/len(l) #求平均数
2.7777777777777777
>>> "{:.3f}".format(sum(l)/len(l)) #求平均数,保留3位小数
'2.778'