2
$\begingroup$

I have two List1:

{{2, -0.6}, {3, -0.9}, {5, -0.5}, {7, -0.4}}

and List2:

{{2, -0.1}, {3, -2}, {5, -2.5}, {7, -3.4}} 

The List1 and List2 have the same first elements in their sublists. Can is it possible to get next List3:

{{2, -0.5}, {3, 1.1}, {5, 2}, {7, 3}} 

where the first elements in sublists the same first elements in the List1 and List2, but at the same time, second elements are difference between the seconds elements from the Lists.

$\endgroup$

3 Answers 3

3
$\begingroup$

We define

lista = {{2, -0.6}, {3, -0.9}, {5, -0.5}, {7, -0.4}};
listb = {{2, -0.1}, {3, -2}, {5, -2.5}, {7, -3.4}};

then we pick the elements

xx = lista[[All, 1]]
yy = (lista - listb)[[All, 2]]

and finally

Thread@{xx, yy}

gives

{{2, -0.5}, {3, 1.1}, {5, 2.}, {7, 3.}}

$\endgroup$
3
$\begingroup$

Without auxiliary variables:

list1 = {{2, -0.6}, {3, -0.9}, {5, -0.5}, {7, -0.4}};

list2 = {{2, -0.1}, {3, -2}, {5, -2.5}, {7, -3.4}};

list1 - list2 . {{0, 0}, {0, 1}}
(* {{2., -0.5}, {3., 1.1}, {5., 2.}, {7., 3.}} *)

The .{{0,0},{0,1}} effectively performs a matrix multiplication on the second list to set the first entries to 0. We can then simply subtract the lists from each other

$\endgroup$
2
$\begingroup$

Another method which allows you to define more complicated operations on your list should you need it in later on:

list1 = {{2, -0.6}, {3, -0.9}, {5, -0.5}, {7, -0.4}};
list2 = {{2, -0.1}, {3, -2}, {5, -2.5}, {7, -3.4}};

operation = {#1[[1]], #1[[2]] - #2[[2]]} &;
MapThread[operation, {list1, list2}] 

(*{{2, -0.5}, {3, 1.1}, {5, 2.}, {7, 3.}}*)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.