This will work in Python 3, which I'm going to assume you're using since you wrote print
as a function. In Python 2 you'll need to make sure that the division is floating point division.
# a = [...]
# Separate the groups. The last slice will be fine with less than 100 numbers.
groups = [a[x:x+100] for x in range(0, len(a), 100)]
# Simple math to calculate the means
means = [sum(group)/len(group) for group in groups]
If you do want to do this in Python 2, you can replace len(group)
in the last line with float(len(group))
, so that it forces floating point division; or, you can add from __future__ import division
at the top of your module, although doing that will change it for the whole module, not just this line.
Here's a nice, reusable version that works with iterators, and is itself a generator:
from itertools import islice
def means_of_slices(iterable, slice_size):
iterator = iter(iterable)
while True:
slice = list(islice(iterator, slice_size))
if slice:
yield sum(slice)/len(slice)
else:
return
a = [1, 2, 3, 4, 5, 6]
means = list(means_of_slices(a, 2))
print(means)
# [1.5, 3.5, 5.5]
You shouldn't make code too much more general than you actually need it, but for bonus experience points, you can make this even more general and composable. The above should be more than enough for your use though.