python - Python 中的运行平均值

标签 python list-comprehension moving-average

是否有一种 Python 式的方法来构建一个包含某个函数的运行平均值的列表?

在阅读了一篇关于 Martians, black boxes, and the Cauchy distribution 的有趣小文章之后,我认为自己计算柯西分布的运行平均值会很有趣:

import math 
import random

def cauchy(location, scale):
    p = 0.0
    while p == 0.0:
        p = random.random()
    return location + scale*math.tan(math.pi*(p - 0.5))

# is this next block of code a good way to populate running_avg?
sum = 0
count = 0
max = 10
running_avg = []
while count < max:
    num = cauchy(3,1)
    sum += num
    count += 1
    running_avg.append(sum/count)

print running_avg     # or do something else with it, besides printing

我认为这种方法可行,但我很好奇是否有比使用循环和计数器(例如 list comprehensions)更优雅的方法来构建 running_avg 列表。

有一些相关的问题,但它们解决了更复杂的问题(小窗口大小、指数权重)或不是特定于 Python 的:

最佳答案

你可以写一个生成器:

def running_average():
  sum = 0
  count = 0
  while True:
    sum += cauchy(3,1)
    count += 1
    yield sum/count

或者,给定一个柯西数生成器和一个运行总和生成器的效用函数,您可以得到一个简洁的生成器表达式:

# Cauchy numbers generator
def cauchy_numbers():
  while True:
    yield cauchy(3,1)

# running sum utility function
def running_sum(iterable):
  sum = 0
  for x in iterable:
    sum += x
    yield sum

# Running averages generator expression (** the neat part **)
running_avgs = (sum/(i+1) for (i,sum) in enumerate(running_sum(cauchy_numbers())))

# goes on forever
for avg in running_avgs:
  print avg

# alternatively, take just the first 10
import itertools
for avg in itertools.islice(running_avgs, 10):
  print avg

关于python - Python 中的运行平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1790550/

相关文章:

python - 在 iPython 中无边框显示的 Pandas 数据框

python - 创建返回过滤对象的 django api View

python - 如何使用理解将整数列表加在一起?

python - Python 中的嵌套列表理解

python - 在 2 个不同的列中做滚动平均并在 Python 中创建一个列

Python - 带有数据框的顺序循环

python - 从文件中提取信息

python - 为什么我的 "if"语句在使用 "break"函数时没有退出?

python - 将排序列表重新映射到字典中

exponential - 使用 Esper 计算指数移动平均线