8

Let's say I have a list

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

I want to get a new_list

new_list = {{0,6},{1,6},{2,8},{3,4},{5,9}}

In this new_list the second element of each pair is a sum of second elements from the original list in which the first elements are similar:

{0,1},{0,2},{0,3} -> {0,1+2+3} -> {0,6};
{1,2},{1,4} -> {1,2+4} -> {1,6};
{2,3},{2,5} -> {2,3+5} -> {2,8};
{3,4} -> {3,4}

Is there a way to do this?

mclord
  • 177
  • 4

2 Answers2

9
GroupBy[list, First -> Last, Total]

<|0 -> 6, 1 -> 6, 2 -> 8, 3 -> 4, 5 -> 9|>

To get to a list form:

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

{{0, 6}, {1, 6}, {2, 8}, {3, 4}, {5, 9}}

lericr
  • 27,668
  • 1
  • 18
  • 64
8

Using GatherBy:

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

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

Using Reap/Sow:

a = Union@(First /@ list)
b = Plus @@@ Last@Reap@Scan[Sow[Last@#, First@#] &, list]
Transpose[{a, b}]

Using Merge:

List @@@ (Merge[Rule @@@ list, Total] // Normal)

Result:

{{0, 6}, {1, 6}, {2, 8}, {3, 4}, {5, 9}}

Syed
  • 52,495
  • 4
  • 30
  • 85