Re: Howto sum up a list?

• To: mathgroup at smc.vnet.net
• Subject: [mg106968] Re: [mg106913] Howto sum up a list?
• From: Leonid Shifrin <lshifr at gmail.com>
• Date: Fri, 29 Jan 2010 07:50:17 -0500 (EST)
• References: <201001280743.CAA23521@smc.vnet.net>

```Hi Jonas,

In[1]:=
data = {{eggs, 4}, {milk, 1}, {eggs, 1}, {milk, 1}};

One possibility:

In[2]:=
Transpose[{#[[All, 1, 1]], Total /@ #[[All, All, 2]]}] &@
GatherBy[data, First]

Out[2]= {{eggs, 5}, {milk, 2}}

One more:

In[3]:= Reap[Sow @@@ Reverse[data, 2], _, {#1, Total@#2} &][[2]]

Out[3]= {{eggs, 5}, {milk, 2}}

Regards,
Leonid

On Thu, Jan 28, 2010 at 10:43 AM, 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: PlotRange All vs Full in ListPlot (bug?)
• 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?