Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Sum elements in a list with conditions
Replies: 5   Last Post: Oct 20, 2012 1:56 PM

 Messages: [ Previous | Next ]
 Simons, F.H. Posts: 107 Registered: 12/7/04
Re: Sum elements in a list with conditions
Posted: Oct 19, 2012 2:49 AM

After having used GatherBy, for each of the resulting list elements you
want to have the first element of the first column and the sum of the
second column:

In[10]:= list1 = {{1,a},{2,b},{1,c},{2,d},{2,e},{3,f}};
In[11]:= {#[[1,1]], Total[#[[All,2]]]}& /@ GatherBy[list1, First]
Out[11]= {{1,a+c},{2,b+d+e},{3,f}}

Fred Simons
Eindhoven University of Technology

Op 18-10-2012 8:36, Guillermo Sanchez schreef:
> 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}]
>
>
>

Date Subject Author
10/19/12 Sseziwa Mukasa
10/19/12 Bob Hanlon
10/19/12 Simons, F.H.