8
$\begingroup$

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?

$\endgroup$

2 Answers 2

8
$\begingroup$

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}}

$\endgroup$
9
$\begingroup$
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}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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