7
$\begingroup$

Suppose I have the following list,

l = {{"b", "c", "d"}, {"e", "b"}, {"a", "b", "d", "e"}}

and further suppose I have the following association,

l1=<|1 -> "a", 2 -> "b", 3 -> "c", 4 -> "d", 5 -> "e"|>

I wonder how can I replace the keys into my list such that I get,

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

The following gives you a "reversed" version of your association, with keys and values flipped:

l1 = <|1 -> "a", 2 -> "b", 3 -> "c", 4 -> "d", 5 -> "e"|>;

lookup = First /@ PositionIndex@l1
(* <|"a" -> 1, "b" -> 2, "c" -> 3, "d" -> 4, "e" -> 5|> *)

You can then use ReplaceAll (/.) to do the replacement:

l = {{"b", "c", "d"}, {"e", "b"}, {"a", "b", "d", "e"}};

l /. lookup
(* {{2, 3, 4}, {5, 2}, {1, 2, 4, 5}} *)

Alternatives

Other possible solutions for creating lookup:

lookup = <|Reverse /@ Normal@l1|>
lookup = Reverse /@ Normal@l1 (* doesn't need to be an association *)
$\endgroup$
10
$\begingroup$

For the specific numbering in OP, you can also use LetterNumber:

LetterNumber[l]

{{2, 3, 4}, {5, 2}, {1, 2, 4, 5}}

$\endgroup$
7
$\begingroup$
l /. Reverse /@ Normal[l1]

(* {{2, 3, 4}, {5, 2}, {1, 2, 4, 5}} *)

or

l /. AssociationMap[Reverse, l1]

(* {{2, 3, 4}, {5, 2}, {1, 2, 4, 5}} *)
$\endgroup$
3
$\begingroup$

For this particular mapping, you could also use ToCharacterCode:

ToCharacterCode[StringJoin /@ l] - First@ToCharacterCode@"a" + 1

{{2, 3, 4}, {5, 2}, {1, 2, 4, 5}}

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