Re: Sum elements in a list with conditions
- To: mathgroup at smc.vnet.net
- Subject: [mg128430] Re: Sum elements in a list with conditions
- From: Bob Hanlon <hanlonr357 at gmail.com>
- Date: Fri, 19 Oct 2012 02:41:03 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- Delivered-to: l-mathgroup@wolfram.com
- Delivered-to: mathgroup-newout@smc.vnet.net
- Delivered-to: mathgroup-newsend@smc.vnet.net
- References: <20121018063647.0023568A4@smc.vnet.net>
list1 = {{1, a}, {2, b}, {1, c}, {2, d}, {2, e}, {3, f}}; list2 = Total[#]/{Length[#], 1} & /@ GatherBy[list1, First] {{1, a + c}, {2, b + d + e}, {3, f}} list2 = list1 //. {s___, {n_, x_}, m___, {n_, y_}, e___} :> {s, {n, x + y}, m, e} {{1, a + c}, {2, b + d + e}, {3, f}} Bob Hanlon On Thu, Oct 18, 2012 at 2:36 AM, Guillermo Sanchez <guillermo.sanchez at hotmail.com> wrote: > I have a list of sublist of pairs. I wish sum the second elements of > the sublists when the first elements are equals > Example: > Int[]:={{1, a}, {2, b}, {1, c}, {2, d}, {2, e}, {3, f}} > I hope > Out[]:= {{1, a + c}, {2, b + c + e}, {3, f}} > > I can do it as is it is shown below but could any body find and > easier solution. > > > list1 = {{1, a}, {2, b}, {1, c}, {2, d}, {2, e}, {3, f}}; > list2 = GatherBy[list1, First]; > {l1, l2} = Transpose[Plus @@@ GatherBy[list, First]]; > Transpose[{l1/Length /@ list2 , l2}] >
- References:
- Sum elements in a list with conditions
- From: Guillermo Sanchez <guillermo.sanchez@hotmail.com>
- Sum elements in a list with conditions