Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

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

Search the Archive

Re: Howto sum up a list?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg106939] Re: [mg106913] Howto sum up a list?
  • From: Fred Simons <f.h.simons at tue.nl>
  • Date: Fri, 29 Jan 2010 07:45:03 -0500 (EST)
  • References: <201001280743.CAA23521@smc.vnet.net>

Jonas Stein wrote:
> How can i sum up the list:
>
> MyList = {{eggs, 4}, {milk, 1}, {eggs, 1}, {milk, 1}}
>
> I want to get something like: 
>
> {{eggs, 5},{milk, 2}}
>
> I tyied Tally[], but that ignored the factor 4 in {eggs, 4}
>
> Thank you. 
>
>   
In this particular case, with  each sublist consisting of a name and a 
number, the following can be used:

List @@@ List @@ Times @@ Power @@@ MyList

More general is

{#[[1, 1]], Total[#[[All, 2]]]} & /@ SplitBy[Sort[MyList], First]

Kind regards,

Fred Simons
Eindhoven University of Technology



  • Prev by Date: Re: Re: Re: More /.{I->-1} craziness. Schools
  • Next by Date: Re: A question about location of points on a circle
  • Previous by thread: Howto sum up a list?
  • Next by thread: Re: Howto sum up a list?