[英]python average of list
Example: A list as示例:列表为
x = [1, 5, 3, 6, 12, 55, 68, 24,]
I want a list of averages with increasing number of elements ie我想要一个元素数量不断增加的平均值列表,即
y = [3, 3, 3.75, 5.4...]
the first element in y is average of first two elements, next is avg of 1st 3 elements, next is avg of 1st 4 elements. y 中的第一个元素是前两个元素的平均值,接下来是第一个 3 个元素的平均值,接下来是第一个 4 个元素的平均值。 The actual list contains thousands of elements.
实际列表包含数千个元素。 Right now doing it by slicing and sum/length.
现在通过切片和总和/长度来做到这一点。 But it takes a long time.
但这需要很长时间。
An O(n) solution would be like this O(n) 解决方案将是这样的
>>>x=[1,2,3,4,5,6,7,8]
>>> ss=x[0]
>>> y=[]
>>> for ind,j in enumerate(x[1:]):
... ss+=j
... y.append(ss*1.0/(ind+2))
...
>>> y
[1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
Mathematical induction yields an algorithm:数学归纳法产生一个算法:
i == 0
, the average of x[0:0] == 0.0
,i == 0
, x[0:0] == 0.0
的平均值,i == 1
, the average of x[0:1] == x[0]
.i == 1
, x[0:1] == x[0]
的平均值。i > 1
the average of x[0:i]
is (x[0:i - 1] + x[i]) / float(i)
.i > 1
, x[0:i]
的平均值是(x[0:i - 1] + x[i]) / float(i)
。 Now we have an incremental algorithm to generate our accumulating average :现在我们有一个增量算法来生成我们的累积平均值:
x = [1, 5, 3, 6, 12, 55, 68, 24,]
def acc_avg(seq):
acc_sum = 0.0
for pos, item in enumerate(seq):
acc_sum += item
# don't forget the float(), otherwise we might be
# running integer division.
yield acc_sum / float(pos + 1)
for z in y:
# this calculates the averages on the fly
print z
# if we need a list, make one from the generator
y = list(acc_avg(x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.