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?
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.
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.
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}}
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}}*)
MapThread[{First@#2,#1}&,{l,ll}]
(* {{1,a},{2,b},{3,c},{4,d}} *)
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}}
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}}
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}}