4

This might seem like a basic operation I have already searched for similar answers but found none. I want to subtract the second elements of my list ct from the corresponding element in lt, and letting the first element to remain as they are the same.

lt={{{1, 1}}, {{2, 1}}, {{3, 1}}, {{2, 3}}, {{5, 1}}, {{2, 4}, {3, 2}}, {{7, 1}}, {{2, 7}}};


ct = {{{1, 1}}, {{2, 1}}, {{3, 1}}, {{2, 2}}, {{5, 1}}, {{2, 1}, {3, 1}}, {{7, 1}}, {{2, 3}}};

as you can see the first elements are the same I want them to remain.

desired result

nt={{{1, 0}}, {{2, 0}}, {{3, 0}}, {{2, 1}}, {{5, 0}}, {{2, 3}, {3, 1}}, {{7, 0}}, {{2, 4}}};

also note that my resulting list nt is my list lt with the last previous first element. like element 4 in my nt is just my element 2 in lt. and where the second element is 0 that means there is no previous first element of the same value, that is a next way to look at it.

Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
Crisp
  • 341
  • 2
  • 7
  • Can you clarify what you mean in the second part? This is rather opaque to me (on a Sunday evening ;). – Ymareth Apr 27 '14 at 18:06
  • oh sorry I just mean that to get my new list nt, I can just use my list lt by looking at the last previous match first elements value. so in my list lt, my first element is {{1,1}} since there is no previouse first value of one, the first element of nt will be {{1,0}} same with element 2 and and 3. but when you reach lt of element four which is {{2,2}}, the last previous element with 2 being the first value is element 2, so nt element four is element 2 of lt which is {{2,1}}. – Crisp Apr 27 '14 at 18:43

4 Answers4

5

You can do:

lt[[;; , ;; , 2]] -= ct[[;; , ;; , 2]];
lt
{{{1, 0}}, {{2, 0}}, {{3, 0}}, {{2, 1}}, {{5, 0}}, {{2, 3}, {3, 1}}, {{7, 0}}, {{2, 4}}}
Kuba
  • 136,707
  • 13
  • 279
  • 740
2

By substitution of zero...

lt-(ct /. {_Integer,x_Integer}:>{0,x})
Ymareth
  • 4,741
  • 20
  • 28
2

Probably not the most elegant way, but works for uneven depths:

rs = lt;
MapIndexed[ If [Element[#1, Integers] && Last@#2 == 2, 
            rs[[Sequence @@ #2]] -= ct[[Sequence @@ #2]]] &, lt, Infinity];
rs
(*
{{{1, 0}}, {{2, 0}}, {{3, 0}}, {{2, 1}}, {{5, 0}}, {{2, 3}, {3, 1}}, {{7, 0}}, {{2, 4}}}
*)
Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
  • @Crisp You can upvote (gray triangle over the score) answers you find useful or are correct. – Kuba Apr 27 '14 at 18:57
2
Map[MapThread[{First[#1], Last[#1] - Last[#2]} &, #] &, Transpose[{lt, ct}]]

{{{1, 0}}, {{2, 0}}, {{3, 0}}, {{2, 1}}, {{5, 0}}, {{2, 3}, {3, 1}}, {{7, 0}}, {{2, 4}}}

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108