itertools.groupby.
Here's how to do it with a nested list comprehension.
from itertools import groupby
from operator import itemgetter
a = [[1,2,3,4,5],[1,2,5,6,7],[1,2,5,2,1],[1,3,4,5,7],[3,4,1,2,3],[3,4,1,1,1]]
expected = [[1,2,13,12,13],[1,3,4,5,7],[3,4,2,3,4]]
print(expected)
a = [list(k) + [sum(t) for t in zip(*[u[2:] for u in g])]
for k, g in groupby(a, itemgetter(0, 1))]
print(a)
Exit
[[1, 2, 13, 12, 13], [1, 3, 4, 5, 7], [3, 4, 2, 3, 4]]
[[1, 2, 13, 12, 13], [1, 3, 4, 5, 7], [3, 4, 2, 3, 4]]
Note that this assumes that the list aalready has sub-lists that start with the same two adjacent elements. If it is not, then it should be sorted, for example
a.sort(key=itemgetter(0, 1))
before running the above code.
Here essentially the same algorithm is broken down for easier reading and analysis.
keyfunc = lambda seq: seq[:2]
a.sort(key=keyfunc)
new_a = []
for k, g in groupby(a, key=keyfunc):
tails = [u[2:] for u in g]
sums = [sum(t) for t in zip(*tails)]
new_a.append(k + sums)
print(new_a)