{
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}
Merge[Total]@{a -> 1, a -> 2, b -> 3, b -> 4}
Normal@
to convert to rules.
$\endgroup$
Commented
Jan 6, 2023 at 6:25
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
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}*)
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]]
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}}