This isn't so much an answer as an attempt at pedagogy. The most canonical answer here is the one from @bmf, but as it stands I fear the OP may not quite grok what's going on.
@mrkhlavkalash, you've asked the question in terms of columns and indices, but the key insight is to see that what you're asking for is the exact functionality provided by ReplaceAll
(which is typically written using the syntactic sugar of /.
. Here's an example of ReplaceAll
:
{1, 2, 3, 1} /. {1 -> "A", 3 -> XYZ}
Result: {"A", 2, XYZ, "A"}
Hopefully, that shows clearly how it works. Notice the 2 didn't get replaced, because there was no rule for 2. Each occurrence of 1 was replaced with "A" and each occurrence of 3 was replaced with the raw symbol XYZ. Our rules are specified with ->
(which is just syntactic sugar for Rule
.
So, in your case, what we want is to end up with this expression somehow:
{1, 2, 1, 3, 2} /. {1 -> a, 3 -> c, 2 -> b}
You're already using a variable to hold the target list, so we really just need
list1 /. {1 -> a, 3 -> c, 2 -> b}
How can we transform list2? Well, {1,a}
is an expression with head List, and we want an expression with head Rule. There is a way to replace a head, and it's called Apply (and yet again, there is a syntac sugar-y form @@
. So,
Rule @@ {1, a}
gives 1 -> a
, aka Rule[1,a]
.
But we need to do this for all of the pairs in list2. This can be done with MapApply
(aka @@@
). So,
Rule @@@ list2
gives {1 -> a, 3 -> c, 2 -> b}
. This is exactly what we need. Putting it together,
list1 /. Rule @@@ list2
which gives {a, b, a, c, b}
.
Okay, I pulled a bit of sleight of hand, because @bmf actually offered
list1 /. Apply[Rule, list2, {1}]
I already discussed Apply, aka @@
, but you can provide an optional argument to specify the level at which to do the Apply-ing, and that's what the {1}
is doing there. We're applying Rule to every element at level 1, and only level 1, in list2.
It's often fun to see how many different ways something can be accomplished in Mathematica, so I offered something slightly different.