下面是如何将一次一个读数添加到运行的读数集合中并返回平均值。我预先填充了readings列表,以便在实际操作中显示它,但是在您的程序中,您将从一个空列表开始:readings = []
我假设你想把最后的x个读数包括在你的平均值中,而不是包括所有的读数。这就是max_samples参数的作用。在
没有numpy:readings = [1, 2, 3, 4, 5, 6, 7, 8, 9]
reading = 10
max_samples = 10
def mean(nums):
return float(sum(nums)) / max(len(nums), 1)
readings.append(reading)
avg = mean(readings)
print 'current average =', avg
print 'readings used for average:', readings
if len(readings) == max_samples:
readings.pop(0)
print 'readings saved for next time:', readings
结果:
^{pr2}$
与numpy:import numpy as np
readings = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
reading = 10
max_samples = 10
readings = np.append(readings, reading)
avg = np.mean(readings)
print 'current average =', avg
print 'readings used for average:', readings
if len(readings) == max_samples:
readings = np.delete(readings, 0)
print 'readings saved for next time:', readings
结果:current average = 5.5
readings used for average: [ 1 2 3 4 5 6 7 8 9 10]
readings saved for next time: [ 2 3 4 5 6 7 8 9 10]