MathGroup Archive 2001

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Summing list subsets

  • To: mathgroup at smc.vnet.net
  • Subject: [mg30761] Re: Summing list subsets
  • From: Tom Burton <tburton at cts.com>
  • Date: Sun, 9 Sep 2001 03:27:21 -0400 (EDT)
  • References: <9ncfgn$prb$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On Sat, 8 Sep 2001 06:57:27 +0000 (UTC), in comp.soft-sys.math.mathematica you wrote:

>x = {a,a,b,b,b,b,c,d,d,d,d,d,} and  y = {1,1,2,2,2,2,3,4,4,4,4,4}
>
>I would like to have a function that returns the sum (or any other function)
>of each unique element of x, given the corresponding value in y. That is,
>for a 'Sum', the result would be
>
>z={{a,2},{b,8},{c,3},{d,20}}

In your example, x is sorted and y is grouped into runs of identical elements in the same pattern as x. I am going to assume, however, that neither of these simplifications hold in general. So here is a three-step scheme to cope with a more realistic case:

1. Combine and sort the two lists.
xy=Sort[Transpose[{x,y}]]


2. Split the lists into runs of identical first elements.
pxy = Split[xy, First[#1] == First[#2] & ]

3. Sum the second elements of each run and (this is most of the work) format as in your example.
({#[[1,1]], Plus @@ #[[All,2]]} & ) /@ pxy

Tom Burton


  • Prev by Date: Re: Summing list subsets
  • Next by Date: Re: algebraic substitution rules
  • Previous by thread: Re: Summing list subsets
  • Next by thread: Re: Summing list subsets