How to sum over duplicates?
Flatten[{#[[1, {1, 2}]], Total[#[[All, 3]]]}] & /@ GatherBy[yourList, #[[{1, 2}]] &]
(* {{1, 0, 4}, {2, 1, 1}, {2, 4, 2}} *)
How this works:
GatherBy[yourList, #[[{1, 2}]] &]
this gathers elements of your list based on matching the first and second elements in each sub-list (#[[{1, 2}]] &
)
Once common elements are gathered (collected) you can total/sum all the third elements by mapping them onto Total
lists = {{1, 0, 1}, {2, 1, 2}, {1, 0, 3}, {2, 4, 2}, {2, 1, -1}, {1, 0, 0}}
Reap/Sow
:
Reap[Sow[#[[3]], {#[[{1, 2}]]}] & /@ lists, _, Append[#1, Total@#2] &][[2]]
ReplaceRepeated
:
lists //. {a___, {x_, y_, z_}, b___, {x_, y_, w_}, c___} :> {a, {x, y, z + w}, b, c}
Cases
+ DeleteDuplicates
:
DeleteDuplicates@Cases[lists, {w : PatternSequence[_, _], _} :>
{w, Total@(Last /@ Cases[lists, {w, _}])}]
all give
{{1, 0, 4}, {2, 1, 1}, {2, 4, 2}}
Update: In versions 10+, you can also use Merge
:
KeyValueMap[Append]@Merge[Tr][Most @ # -> Last @ #& /@ lists]
{{1, 0, 4}, {2, 1, 1}, {2, 4, 2}}
Total@#/PadLeft[{1}, 3, Length@#] & /@ GatherBy[list, #[[{1, 2}]] &]
This approach is basically the same as Mike's. However, instead of summing only the last element it sums all the elements. To correct for the extra summing PadLeft[{1}, 3, Length@#]
is used to divide by the number of times it was added where the {1}
is included to keep the last element the same. The approach can be generalized to lists of length $n$ by replacing PadLeft[{1}, 3, Length@#]
with PadLeft[{1}, Length@#[[1]], Length@#]