6
{
 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}
我心永恒
  • 1,488
  • 6
  • 9

4 Answers4

12

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

rnotlnglgq
  • 3,740
  • 7
  • 28
6

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

bmf
  • 15,157
  • 2
  • 26
  • 63
5

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}*)
E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
4
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]]
user1066
  • 17,923
  • 3
  • 31
  • 49