Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2006
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2006

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

Search the Archive

Re: Sum elements in a list with conditions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg69847] Re: Sum elements in a list with conditions
  • From: jmhigg at gmail.com
  • Date: Mon, 25 Sep 2006 03:53:19 -0400 (EDT)
  • References: <ef5066$mm5$1@smc.vnet.net>

Guillermo,

You can try this:

(i) First use Split with your own test function to split up the pairs
that have  the same first element:

ls = {{a1, b1}, {a2, b2}, {a2, b3}, {a2, b4}, {a3, b5}, {a3, b6}} ;


Split[ls,(First[#1]==First[#2])&]

{{{a1,b1}},{{a2,b2},{a2,b3},{a2,b4}},{{a3,b5},{a3,b6}}}

(ii) Then map Fold onto each sublist above to add the second element of
that sublist
Here is the final result as single line of code:


Map[{First[Flatten[#]],Fold[(#1+Last[#2])&,0,#]}&,Split[ls,(First[#1]==First[#2])&]]


{{a1,b1},{a2,b2+b3+b4},{a3,b5+b6}}

Cheers,

Brian

Guillermo Sanchez wrote:
> Dear group
> I have a pair of elements list. The second elements of the list should
> be summed when the first element of the pairs are equals. Example
>
> Given
>
> {{a1, b1},{a2,b2},{a2,b3},{a2,b4},{a3, b5}, {a3, b6}}
>
> the output should be
> 
> {{a1, b1},{a2, b2+b3+b4},{a3, b5+b6}}
> 
> Thanks 
> 
> Guillermo


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