4

Imagine following list

list = {{0, 3}, {1, 1}, {1, 2}, {2, 3}, {2, 4}}

I would like to get the result

{{0, 3}, {1, 3}, {2, 7}}

i.e., grouping by the first element of the tuples in the list, summing the second element of all tuples that share the same first element.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257

1 Answers1

4

Summary of the methods given in the comments to the question.

data = {{0, 3}, {1, 1}, {1, 2}, {2, 3}, {2, 4}};

swish (requires V10 or later)

KeyValueMap[List, GroupBy[data, First -> Last, Total]]

m_goldberg (requires V7 or later)

{#1[[1, 1]], Total[#[[2]]]} & /@ Transpose /@ GatherBy[data, First]

Mr.Wizard

Rule @@@ list // Merge[Total] // KeyValueMap[List]

All the above return

{{0, 3}, {1, 3}, {2, 7}}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
m_goldberg
  • 107,779
  • 16
  • 103
  • 257