Well this didn't come out too readable - but here's a pretty compact way with itertools.groupby
and reduce
:
from itertools import groupby
from operator import itemgetter as ig
[reduce(lambda x,y: x[:-1] + [x[-1] + y[-1]], g) for k,g in groupby(sorted(lst, key=ig(1)), ig(1))]
Out[26]:
[['aaa', 'key1', 'abc', 10],
['aaa', 'key2', 'abc', 14],
['ddd', 'key3', 'abc', 4]]
Things get better if you pull out the lambda into a helper function:
def helper(agg,x):
agg[-1] += x[-1]
return agg
[reduce(helper,g) for k,g in groupby(sorted(lst, key=ig(1)), ig(1))]
Out[30]:
[['aaa', 'key1', 'abc', 10],
['aaa', 'key2', 'abc', 14],
['ddd', 'key3', 'abc', 4]]
Note that you'll need to do from functools import reduce
in python 3, since it got banished from the builtins (sad face).