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: [mg106970] Re: [mg106913] Howto sum up a list?
  • From: Bob Hanlon <hanlonr at cox.net>
  • Date: Fri, 29 Jan 2010 07:50:39 -0500 (EST)
  • Reply-to: hanlonr at cox.net

myList = {{eggs, 4}, {milk, 1},
   {eggs, 1}, {milk, 1}};

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

{{eggs, 5}, {milk, 2}}

{#, Total[Cases[myList, {#, n_} :> n]]} & /@
 Union[myList[[All, 1]]]

{{eggs, 5}, {milk, 2}}

myList //.
 {s___, {t_, j_}, m___, {t_, k_}, 
   e___} :>
  {s, {t, j + k}, m, e}

{{eggs, 5}, {milk, 2}}


Bob Hanlon

---- Jonas Stein <news 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 <news at jonasstein.de>



  • Prev by Date: Re: Howto sum up a list?
  • Next by Date: Re: Howto sum up a list?
  • Previous by thread: Re: Howto sum up a list?
  • Next by thread: Re: Howto sum up a list?