2
$\begingroup$

I have one list like this {{1, 3}, {2, 5}} and another like this {1,2}, so I want to do first list minus second so that result will be {{1, 2}, {2, 3}}. How can I do this?

$\endgroup$
4
$\begingroup$

Try MapThread

list1={{1, 3}, {2, 5}};list2={1,2};
MapThread[#1-{0,#2}&,{list1,list2}]

which instantly gives you

{{1,2},{2,3}}

Study the documentation and see if you can figure out how this works. It takes corresponding pairs of items from each list and does a function to them, in this case doing your subtraction on part of the first list.

If this & and # stuff is confusing then an equivalent solution that perhaps makes the function more understandable is

list1={{1, 3}, {2, 5}};list2={1,2};
f[v1_,v2_]:=v1-{0,v2};
MapThread[f,{list1,list2}]

That will do

{1,3}-{0,1}=={1,2}

and then do

{2,5}-{0,2}=={2,3}

giving you your desired

{{1,2},{2,3}}

A completely different way of doing this is to turn your two lists into exactly the same shape and size matricies and then just subtract the two matricies.

list1-Map[{0,#}&,list2]

which gives you

{{1,2},{2,3}}
$\endgroup$
4
$\begingroup$

There are many approaches. These also works.

list1 = {{1, 3}, {2, 5}};
list2 = {1, 2};

Transpose@(Transpose@list1 - {{0, 0}, list2})
(* {{1, 2}, {2, 3}} *)

or

list1 - Transpose@{{0, 0}, list2}

which gives the same answer.

$\endgroup$
2
$\begingroup$

I didn't at first understand the problem statement. We are subtracting the second list from the second element of the first list.

With that understanding, here is another possibility:

Transpose[{list1[[;; , 1]], list1[[;; , -1]] - list2}]

This method is using "spans" to pair the first elements of list1 with the second (last) element of list1 minus list2.

$\endgroup$
1
$\begingroup$
l1 = {{1, 3}, {2, 5}}; 
l2 = {1, 2};

A few additional alternatives:

SubsetMap[# - l2 &, l1, {All, 2}]

{{1, 2}, {2, 3}}

l3 = l1; l3[[All, 2]] -= l2; l3

{{1, 2}, {2, 3}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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