7
$\begingroup$

I have two lists as follow:

l={a,b,c,d}

and

ll={{1,x},{2,x},{3,x},{4,x}}

I want to replace the x's with a,b,c and d so that the outcome would be:

{{1,a},{2,b},{3,c},{4,d}}

How would one does this?

$\endgroup$

8 Answers 8

8
$\begingroup$

This should make the job:

ll[[;; , 2]] = l;
ll

{{1, a}, {2, b}, {3, c}, {4, d}}

Or equivalently:

MapThread[#1 /. {x -> #2} &, {ll, l}]

{{1, a}, {2, b}, {3, c}, {4, d}}

Note that the output is the same, but what the code is doing is different, and you might prefer one solution or the other depending on your specific case.

$\endgroup$
7
$\begingroup$
Transpose[{ll[[All, 1]], l}]

{{1, a}, {2, b}, {3, c}, {4, d}}

My preferred method would be the first method proposed in Fraccalo's answer.

$\endgroup$
2
$\begingroup$
la = {a, b, c, d};

lb = {{1, x}, {2, x}, {3, x}, {4, x}};

Using SubsetMap (new in 12.0)

SubsetMap[la &, lb, {All, -1}]

{{1, a}, {2, b}, {3, c}, {4, d}}

$\endgroup$
2
$\begingroup$
l = {a, b, c, d};
ll = {{1, x}, {2, x}, {3, x}, {4, x}};

Using Thread:

Thread[{ll[[All, 1]], l}]

(*{{1, a}, {2, b}, {3, c}, {4, d}}*)
$\endgroup$
2
$\begingroup$
MapThread[{First@#2,#1}&,{l,ll}]

(* {{1,a},{2,b},{3,c},{4,d}} *)
$\endgroup$
2
$\begingroup$
la = {a, b, c, d};

lb = {{1, x}, {2, x}, {3, x}, {4, x}};

Using Cases

Cases[{a_, {b_, _}} :> {b, a}] @ Transpose[{la, lb}]

{{1, a}, {2, b}, {3, c}, {4, d}}

$\endgroup$
1
$\begingroup$

Using ReplacePart:

l = {a, b, c, d}
ll = {{1, x}, {2, x}, {3, x}, {4, x}}

ReplacePart[ll, Thread[Position[ll, x] -> l]]

{{1, a}, {2, b}, {3, c}, {4, d}}

$\endgroup$
1
$\begingroup$
l = {a, b, c, d};

ll = {{1, x}, {2, x}, {3, x}, {4, x}};

Another way, using Replace at level 1:

Module[{i = 1}, Replace[ll, {a_, b_} :> {a, l[[i++]]}, 1]]

{{1, a}, {2, b}, {3, c}, {4, d}}

$\endgroup$

Your Answer

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

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