This post originated from an RSS feed registered with Python Buzz
by Thomas Guest.
Original Post: Python averages
Feed Title: Word Aligned: Category Python
Feed URL: http://feeds.feedburner.com/WordAlignedCategoryPython
Feed Description: Dynamic languages in general. Python in particular. The adventures of a space sensitive programmer.
You’ve been running some tests, each of which returns a 3-tuple of numerical results — (real, user, sys) times, maybe — and you’d like to combine these into a single 3-tuple, the average result.
Easy!
def average(times):
N = float(len(results))
return (sum(t[0] for t in times)/N,
sum(t[1] for t in times)/N,
sum(t[2] for t in times)/N)
If you want a more generic solution, one which works when the tuples might have any number of elements, you could do this:
def average(xs):
N = float(len(xs))
R = len(xs[0])
return tuple(sum(x[i] for x in xs)/N for i in range(R))
or this:
def average(xs):
N = float(len(xs))
return tuple(sum(col)/N for col in zip(*xs))
The second generic variant uses zip to transpose its inputs.
Now suppose we have keyed collections of results which we want to average:
A Counter can collect and calculate the average fridge contents.
>>> from collections import Counter
>>> total = sum(map(Counter, fridges), Counter())
>>> N = float(len(fridges))
>>> { k: v/N for k, v in total.items() }
{'sausage': 2.5, 'lettuce': 0.25, 'beer': 1.5, 'carrot': 1.0,
'egg': 2.25, 'milk': 0.59825}
Note that although Counters were primarily designed to work with positive integers to represent counts, there’s nothing stopping us from using floating point numbers (amount of milk in our example) in the values field.