4
$\begingroup$

I have a list containing one of four symbolic codes and would like to assign a number to each based on the index for each element in a second list "dictionary' containing one of each code.

typecode = Table[i, {i, 4}]

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

typestrings = {"AA", "Aa", "aA", "aa"}

(* {"AA", "Aa", "aA", "aa"} *)

alist = RandomChoice[typestrings, 10]

(* {"Aa", "aa", "aa", "aa", "Aa", "aA", "AA", "AA", "aa", "aA"} *)

Table[Extract[ 
        typecode , 
        Flatten[Position[typestrings, alist[[i]] ]] 
        ] , {i, 10 } ]

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

works but feels awfully inelegant. Any suggestions?

$\endgroup$
1
  • 1
    $\begingroup$ Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$ – Michael E2 Apr 30 '18 at 2:46
5
$\begingroup$

You can use an Association as dictionary:

typecode = Table[i, {i, 4}];
typestrings = {"AA", "Aa", "aA", "aa"};
dictionary = AssociationThread[typestrings, typecode]

RandomSeed[666];
alist = RandomChoice[typestrings, 10000];

a = Table[
     Extract[typecode, 
      Flatten[Position[typestrings, alist[[i]]]]], {i, 
      Length[alist]}]; // AbsoluteTiming // First
b = Lookup[dictionary, alist]; // AbsoluteTiming // First
a == b

<|"AA" -> 1, "Aa" -> 2, "aA" -> 3, "aa" -> 4|>

0.043401

0.000695

True

As you can see, this is also much faster.

$\endgroup$
3
  • $\begingroup$ Thanks so much. This is good. $\endgroup$ – jmm Apr 21 '18 at 14:18
  • $\begingroup$ @jmm As a courtesy, remember to accept Henrik's answer if you choose it. $\endgroup$ – Alan Apr 21 '18 at 15:34
  • $\begingroup$ @jmm You're welcome! $\endgroup$ – Henrik Schumacher Apr 22 '18 at 0:19
3
$\begingroup$
alist /. Thread[typestrings -> typecode]

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

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