2
$\begingroup$

I have two lists and I want to take the difference keeping the first elements of the sublists ( X1,X2 below) intact which are the same in both lists. Is there any easier way to do it without explicitly going through each list element and taking the differences except the first one? I tried

listA = {{1}, {X1, a, b}, {X2, c, d}};
listB = {{0}, {X1, a0, b0}, {X2, c0, d0}};
MapThread[{First[#1] , Rest[#1] - Rest[#2]} &, {listA, listB}] 

Output:

{{1, {}}, {X1, {a - a0, b - b0}}, {X2, {c - c0, d - d0}}}

Expected output:

{{1}, {X1, a - a0, b - b0}, {X2, c - c0, d - d0}}

How do I remove these unwanted braces?

$\endgroup$
4
  • 1
    $\begingroup$ Flatten[#, 1] & /@ MapThread[{First[#1], Rest[#1] - Rest[#2]} &, {listA, listB}] $\endgroup$
    – Syed
    Dec 14, 2022 at 16:22
  • $\begingroup$ I did use Flatten but as //Flatten which removed all the braces which is why it did not work. $\endgroup$
    – BabaYaga
    Dec 14, 2022 at 17:44
  • $\begingroup$ MapThread[{First[#1], Sequence @@ (Rest[#1] - Rest[#2])} &, {listA, listB}] $\endgroup$ Dec 14, 2022 at 22:52
  • $\begingroup$ If you have at least version 12.1 then consider also MapThread[{First[#1], Splice[Rest[#1] - Rest[#2]]} &, {listA, listB}] $\endgroup$ Dec 14, 2022 at 22:54

2 Answers 2

2
$\begingroup$

Try this:

 MapThread[
 Flatten@{First[#1], 
 If[SameQ[Rest[#], {}], Nothing, Rest[#1] - Rest[#2]]} &, {listA, listB}]
$\endgroup$
1
$\begingroup$
listA = {{1}, {X1, a, b}, {X2, c, d}};
listB = {{0}, {X1, a0, b0}, {X2, c0, d0}};

Expected output:

{{1}, {X1, a - a0, b - b0}, {X2, c - c0, d - d0}}


listA - listB // ReplacePart[{i_, 1} :> listA[[i, 1]]]

{{1}, {X1, a - a0, b - b0}, {X2, c - c0, d - d0}}

$\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.