Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

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


Math Forum » Discussions » Software » comp.soft-sys.math.mathematica

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

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Sseziwa Mukasa

Posts: 108
Registered: 8/26/07
Re: Sum elements in a list with conditions
Posted: Oct 19, 2012 2:47 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

There's no need to transpose:

{#[[1, 1]], Total[#[[All, 2]]]} & /@GatherBy[list1,First]

On Oct 18, 2012, at 2:36 AM, Guillermo Sanchez wrote:

> 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}]
>






Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.