Link to a list of word positions
I have a list of words that I created with the Input statement: phrase = enter (enter phrase :) My name is my name
phrase.split()
Phrase = ["My", "Name", "Is", "My", "Name", "Is"]
Then I created a UsedWords list (see below) by listing the list of phrases and adding all the words that were used to create the original phrase.
WordsUsed = ["My","Name","Is"]
indexOfWords=[0 1 2 ]
Then I saved the index of each letter (in the WordsUsed list) into a new list called indexOfWords using a built-in method.
So now I want to repeat the creation of the original phrase in the phrase list, but replace it with the Word index in the WordsUsed list. For example:
Phrase = ["My", "Name", "Is", "My", "Name", "Is"]
WordsUsed = ["My","Name","Is"]
NewPhrase = [0, 1, 2, 0, 1, 2]
I tried as Kasra suggested the following:
d={j:i for i,j in enumerate(set(Phrase))}
[d[i] for i in Phrase]
However, this returns the following output for the phrase: Phrase = ["My", "Name", "Is", "My", "Name", "Is"] [2, 1, 0, 2, 1, 0] I believe that it outputs the lexicography of the list. The actual output must be [0, 1, 2, 0, 1, 2]
Does anyone have any ideas on how to overcome this.
Greetings
Try:
[WordsUsed.index(word) for word in Phrase]
What does he give you
Considering ["My", "Name", "Is", "My", "Name", "Is"]
you get [0, 1, 2, 0, 1, 2]
.
Considering ["My", "Name", "My", "My", "Name"]
you get [0, 1, 0, 0, 1]
.
Hopefully this is a more readable and compact answer.