weekly = [ sum(visitors[x:x+7]) for x in range(0, len(daily), 7)]
Or a little less tight:
weekly = [] for x in range(0, len(daily), 7): weekly.append( sum(visitors[x:x+7]) )
Alternatively using the numpy module.
by_week = numpy.reshape(visitors, (7, -1)) weekly = numpy.sum( by_week, axis = 1)
Please note that this requires that the number of visitors per visitor be a multiple of 7. It also requires numpy installation. However, it is probably also more effective than other approaches.
Or for the itertools code bonus:
def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return itertools.izip_longest(fillvalue=fillvalue, *args) weekly = map(sum, grouper(7, visitors, 0))
Winston ewert
source share