Message Boards Message Boards

0
|
5408 Views
|
3 Replies
|
3 Total Likes
View groups...
Share
Share this post:

List rearrangement and summing

Hi,

I have a list of the form:
{{a, x, y}, {b, x, x}, {c, y, y}, {d, x, y}, {e, y, y}}
How can I  rearrange it to:
{{a + d, x, y}, {b, x, x}, {c + e, y, y}}
i.e. to sum 1st elements for all sublists with equal 2nd and 3d elements

Thanks,
I.M.
POSTED BY: Ivan Morozov
3 Replies
Thanks!
The second way is indeed better for me, since it doesn't depend on sublists length.
POSTED BY: Ivan Morozov
Posted 11 years ago
How about:
 sumFirstColumn[M_] := Prepend[
   M[[1, 2 ;; -1]],
   Total[M[[All, 1]]]
 ]
 
 lis = {{a, x, y}, {b, x, x}, {c, y, y}, {d, x, y}, {e, y, y}};
 grouped = GatherBy[lis, Rest];
 sumFirstColumn /@ grouped
 
(* {{a + d, x, y}, {b, x, x}, {c + e, y, y}} *)
POSTED BY: Greg Hurst
Posted 11 years ago
Every time you have:
maybe some stuff,
then a sublist with the right tail,
maybe some more stuff,
then another sublist with the same tail
and maybe some last stuff
then
replace all that with
the first stuff, the revised sublist, the more stuff and the last stuff
and repeat all that over and over until there are no more changes to make.
In[1]:= {{a,x,y},{b,x,x},{c,y,y},{d,x,y},{e,y,y}}//.{h___,{p_,q_,r_},m___,{s_,q_,r_},t___}:>{h,{p+s,q,r},m,t}

Out[1]= {{a+d,x,y}, {b,x,x}, {c+e,y,y}}
Think of a more efficient method if you list has millions or tens of millions of sublists.
POSTED BY: Bill Simpson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract