Find sum of subsets of a list in python

This is probably very simple, and I'm missing something ...

I have a long list of integers, in this case representing daily website visitors. I want a new list of weekly visitors. So I need to get groups of seven from the original list, sum them up and add them to the new list.

My solution seems pretty brute force, inelegant:

numweeks = len(daily) / 7 weekly = [] for x in range(numweeks): y = x*7 weekly.append(sum(visitors[y:y+7])) 

Is there a more efficient or more pythonic way to do this?

+8
python list chunks
source share
3 answers
 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)) 
+10
source share
 >>> daily = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] >>> print [sum(daily[x:x+7]) for x in range(0, len(daily), 7)] [28, 77, 105] 

I'm not sure if this is "pythonic", but I really love this one-line python stuff.

Gory Details: Comprehensions

0
source share

Using itertools.islice:

 weekly = [sum(list(itertools.islice(daily, i, i+7))) for i in range(0, len(daily), 7)] 

Edit:

or using math.fsum:

 weekly = [math.fsum(itertools.islice(daily, i, i+7)) for i in range(0, len(daily), 7)] 
0
source share

All Articles