Re: Sum elements in a list with conditions

*To*: mathgroup at smc.vnet.net*Subject*: [mg69844] Re: [mg69828] Sum elements in a list with conditions*From*: "Adriano Pascoletti" <pascolet at dimi.uniud.it>*Date*: Mon, 25 Sep 2006 03:53:13 -0400 (EDT)

Guillermo Sanchez wrote .. > Dear group > I have a pair of elements list. The second elements of the list should > be summed when the first element of the pairs are equals. Example > > Given > > {{a1, b1},{a2,b2},{a2,b3},{a2,b4},{a3, b5}, {a3, b6}} > > the output should be > > {{a1, b1},{a2, b2+b3+b4},{a3, b5+b6}} > A solution with Sow and Reap In[1]:= L = {{a1, b1}, {a2, b2}, {a2, b3}, {a2, b4}, {a3, b5}, {a3, b6}}; In[2]:= Reap[(Sow[#1[[2]], #1[[1]]] & ) /@ L, _, {#1, Total[#2]} & ][[2]] Out[2]= {{a1, b1}, {a2, b2 + b3 + b4}, {a3, b5 + b6}} Adriano Pascoletti