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: [mg106972] Re: Howto sum up a list?
  • From: prashanth <prash.mr at gmail.com>
  • Date: Fri, 29 Jan 2010 07:51:00 -0500 (EST)
  • References: <hjrf6g$mur$1@smc.vnet.net>

On Jan 28, 12:43 pm, Jonas Stein <n... at jonasstein.de> 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.
>
> --
> Jonas Stein <n... at jonasstein.de>




The below is a brute-force way fo summing up. it is not really
efficient for a larger no. of variables. but, it will work fairly
decently.
MyList = {{eggs, 4}, {milk, 1}, {eggs, 1}, {milk, 1}}
eggstab =Table[MyList[[All, 1]][[i]] == eggs, {i, 1, Length[MyList]}];
milktab =Table[MyList[[All, 1]][[i]] == milk, {i, 1, Length[MyList]}];
epos = Position[eggstab, True];
mpos = Position[milktab, True];
etot = Total[Extract[MyList[[All, 2]], epos]];
mtot = Total[Extract[MyList[[All, 2]], mpos]];
Print[{{"eggs", etot}, {"milk", mtot}}]


  • Prev by Date: Re: looping
  • Next by Date: Re: Ha! a document that FAILS because it is in notebook
  • Previous by thread: Re: Howto sum up a list?
  • Next by thread: Re: Journals dying?, apparently rather slowly (was , I->-I)