groupby - summing multiple columns in a list of lists
Jackson
jackcwoodhead at googlemail.com
Tue May 17 13:01:23 EDT 2011
I'm currently using a function pasted in below. This allows me to sum
a column (index) in a list of lists.
So if mylist = [[1, 2, 3], [1, 3, 4], [2, 3, 4], [2, 4, 5]]
group_results(mylist,[0],1)
Returns:
[(1, 5), (2, 7)]
What I would like to do is allow a tuple/list of index values, rather
than a single index value to be summed up, so you could say
group_results(mylist,[0],[1,2]) would return [(1, 5,7), (2, 7,9)] but
I'm struggling to do so, any thoughts? Cheers
from itertools import groupby as gb
from operator import itemgetter as ig
def group_results(table,keys,value):
res = []
nkey = ig(*keys)
value = ig(value)
for k, group in gb(sorted(table,key=ig(*keys)),nkey):
res.append((k,sum(value(row) for row in group)))
return res
More information about the Python-list
mailing list