2
$\begingroup$

I have data in form of:

data={{1,1,3},{1,1,6},{2,1,7},{2,2,4},{2,1,1}};

I want to match the entries with the same first two elements and add the third element in matching entries, so the result would be:

result={{1,1,9},{2,1,8},{2,2,4}}

For now, this is accomplished by using matching rules, like this:

data//.{h___, {x_, y_, z_}, b___, {x_, y_, f_}, t___} :> {h, {x, y, z + f}, b, t};

Needless to say, the procedure gets painfully slow with lists longer than a few hundred entries. I'm trying to come up with faster alternatives, I already looked at the examples with 1 matching element, but I can't quite expand it to two elements as I'm still fairly unfamiliar with all the operators and procedures.

Regards, blairo

$\endgroup$

marked as duplicate by Kuba, Mr.Wizard list-manipulation May 9 '16 at 12:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 3
    $\begingroup$ How about KeyValueMap[Append, GroupBy[data, Take[#, 2] &, Total[#[[All, -1]]] &]]? $\endgroup$ – J. M. will be back soon May 9 '16 at 11:52
  • $\begingroup$ @J.M. unfortunately, I'm limited to V10.0. $\endgroup$ – blairo May 9 '16 at 12:01
  • 1
    $\begingroup$ @J.M. no # example: KeyValueMap[Append, GroupBy[data, Most, Last@*Total]] $\endgroup$ – Kuba May 9 '16 at 12:13
  • $\begingroup$ See also: (17734) $\endgroup$ – Mr.Wizard May 9 '16 at 12:20
  • $\begingroup$ @Kuba, that'll work, but I feel that Last@*Total wastes a few additions. $\endgroup$ – J. M. will be back soon May 9 '16 at 12:56

Browse other questions tagged or ask your own question.