Re: Howto sum up a list?
- To: mathgroup at smc.vnet.net
- Subject: [mg106964] Re: Howto sum up a list?
- From: JH <jlucio at ubu.es>
- Date: Fri, 29 Jan 2010 07:49:34 -0500 (EST)
- References: <hjrf6g$mur$1@smc.vnet.net>
On 28 ene, 08:43, 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> Hello, Jonas: You can try this: MyList = {{eggs,4},{milk,1},{eggs,1},{milk,1}}; listgather = Gather[MyList, #1[[1]] == #2[[1]] &]; Table[{listgather[[i,1,1]], Total[listgather[[i,All,2]]]},{i,Length [listgather]}] The output is what you expected (grouping by first element and summing second element in each group): {{eggs, 5}, {milk, 2}} I hope it helps you. JH