MathGroup Archive 2012

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Sum elements in a list with conditions


A solution with Sow and Reap

In[1]:= L = {{1, a}, {2, b}, {1, c}, {2, d}, {2, e}, {3, f}};
  Reap[(Sow @@ Reverse[#1] & ) /@ L, _, {#1, Total[#2]} & ][[2]]
Out[1]= {{1, a + c}, {2, b + d + e}, {3, f}}

Adriano Pascoletti

2012/10/18 Guillermo Sanchez <guillermo.sanchez at hotmail.com>

> I have a list of sublist of pairs. I wish sum the second elements of
> the sublists when the first elements are equals
> Example:
> Int[]:={{1, a}, {2, b}, {1, c}, {2, d}, {2, e}, {3, f}}
> I hope
> Out[]:= {{1, a + c}, {2, b + c + e}, {3, f}}
>
> I can do it as  is it is shown below but could any body find and
> easier solution.
>
>
> list1 = {{1, a}, {2, b}, {1, c}, {2, d}, {2, e}, {3, f}};
> list2 = GatherBy[list1, First];
> {l1, l2} = Transpose[Plus @@@ GatherBy[list, First]];
> Transpose[{l1/Length /@ list2 , l2}]
>
>




  • Prev by Date: Re: Sum elements in a list with conditions
  • Next by Date: More Button crashes
  • Previous by thread: Re: Sum elements in a list with conditions
  • Next by thread: Re: Sum elements in a list with conditions