# List rearrangement and summing

Posted 10 years ago
4485 Views
|
3 Replies
|
3 Total Likes
|
 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 elementsThanks,I.M.
3 Replies
Sort By:
Posted 10 years ago
 Thanks!The second way is indeed better for me, since it doesn't depend on sublists length.
Posted 10 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 10 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 withthe 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.