6
$\begingroup$
{
 a -> 1,
 a -> 2,
 b -> 3,
 b -> 4
 }

You can see that both a and b have two values, so how do I add these two vaule?Like this

{a->3,b->7}
$\endgroup$

5 Answers 5

12
$\begingroup$

Merge[Total]@{a -> 1, a -> 2, b -> 3, b -> 4}

$\endgroup$
1
  • 6
    $\begingroup$ Or preface with Normal@ to convert to rules. $\endgroup$
    – Bob Hanlon
    Commented Jan 6, 2023 at 6:25
7
$\begingroup$

Another suggested solution is suggested below.

The logic is to transform the list of rules into a list of lists, sort it and then sum over.

With

lst = {a -> 1, a -> 2, b -> 3, b -> 4};

we do

Rule @@@ ({#[[1, 1]], Total[#[[All, 2]]]} & /@ 
   GatherBy[Sort[List @@@ lst], First])

having borrowed from Syed

The above returns

res

$\endgroup$
7
$\begingroup$

Just another way to do this using GroupBy:

Map[Part[#, 1] -> Total@Part[#, 2, All, 2] &, Normal@GroupBy[lst, Keys]]
(*{a -> 3, b -> 7}*)

Or in a compact way using the third argument of GroupBy:

Normal@GroupBy[lst, Keys,Total@#[[All, 2]] &]
(*{a -> 3, b -> 7}*)
$\endgroup$
5
$\begingroup$
Reap[MapApply[Sow[#2,#1]&]@rules,_,#1->Total@#2&][[2]]

(* {a -> 3, b -> 7} *) 

Original Answer

Reap[Sow[Last@#,First@#]&/@rules,_,#1->Total[#2]&][[2]]
$\endgroup$
2
$\begingroup$
list = {a -> 1, a -> 2, b -> 3, b -> 4};

A variant of E. Chan-López GroupBy-solution

GroupBy[list, First -> Last, Total]

<|a -> 3, b -> 7|>

KeyValueMap[List][%]

{{a, 3}, {b, 7}}

$\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.