MathGroup Archive 2006

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

Search the Archive

Re: Sum elements in a list with conditions


Guillermo,

First collect the sublists containing identical first elements using
Split:

In[4]:=
alist={{a1, b1},{a2,b2},{a2,b3},{a2,b4},{a3, b5}, {a3, b6}};
In[5]:=
Split[{{a1, b1},{a2,b2},{a2,b3},{a2,b4},{a3, b5}, {a3, b6}},
  First@#1===First@#2&]
Out[5]=
{{{a1,b1}},{{a2,b2},{a2,b3},{a2,b4}},{{a3,b5},{a3,b6}}}

Then you can perform the summation in a variety of ways.  For example:

In[6]:=
%5/.b:{{a_,_}..}:>{a,Plus@@Transpose[b][[2]]}
Out[6]=
{{a1,b1},{a2,b2+b3+b4},{a3,b5+b6}}

dkr


  • Prev by Date: ArcTan[-Infinity, y] always returning 0?
  • Next by Date: Graphics`SurfaceOfRevolution -- axis change
  • Previous by thread: Sum elements in a list with conditions
  • Next by thread: Re: Sum elements in a list with conditions