3
$\begingroup$

Consider we have:

list = {{2, 3}, {3, 30}, {3, 2}, {4, 53}}

and we want to compare the first elements and sum the second elements if first elements are similar them we should get a array

newlist = {{2, 3}, {3, 32}, {4, 53}}

So I did the instruction bellow that did not workout.

Table[if[list[[i, 1]] == list[[i + 1, 1]], 
 {list[[i, 1]], list[[i, 2]] + list[[i + 1, 2]]}, 
 {list[[i, 1]], list[[i, 2]]}], {i, Length[list] - 1}]

How to work around?

$\endgroup$

marked as duplicate by Mr.Wizard Jul 8 '15 at 16:29

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.

  • $\begingroup$ Use If instead of if. Also take a look at patterns -- should be able to cope with difficulty. $\endgroup$ – Sektor Jul 4 '15 at 9:55
5
$\begingroup$

There are a few approaches to this, e.g.

Last@Reap[Sow[#2, #1] & @@@ list, _, {#1, Total@#2} &]

or

List @@@ Normal[GroupBy[list, First -> Last, Total]]

or

{1/Length@#, 1} Total[#] & /@ GatherBy[list, First]

All yield:

{{2, 3}, {3, 32}, {4, 53}}
$\endgroup$
2
$\begingroup$

Using patterns

list = {{2, 3}, {3, 30}, {3, 2}, {4, 53}};

list //. {s___, {a_, x_}, m___, {a_, y_}, e___} :>
  {s, {a, x + y}, m, e}

{{2, 3}, {3, 32}, {4, 53}}

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.