Reputation: 143
I have a list of words which I have created through an Input statement: phrase = input(Please enter a phrase:) My Name Is My Name Is
phrase.split()
Phrase = ["My", "Name", "Is", "My", "Name", "Is"]
I have then created a UsedWords list (see below) by enumerating through the Phrase list and appending all the Words that were used to create the original phrase.
WordsUsed = ["My","Name","Is"]
indexOfWords=[0 1 2 ]
I then stored the index of each letter (within the WordsUsed list) into a new list called indexOfWords by using the built-in in method.
So, what I want to do now is re-create the original phrase within the phrase list, but replace it by the index of the Word in the WordsUsed list. So for example:
Phrase = ["My", "Name", "Is", "My", "Name", "Is"]
WordsUsed = ["My","Name","Is"]
NewPhrase = [0, 1, 2, 0, 1, 2]
I have tried as suggested by Kasra 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"] output [2, 1, 0, 2, 1, 0] I belive that it is outputting the list lexicographicaly. The Actual output should be [0, 1, 2, 0, 1, 2]
Does anybody have any ideas on how to overcome this.
Cheers
Upvotes: 3
Views: 83
Reputation: 2259
Try:
[WordsUsed.index(word) for word in Phrase]
Given ["My", "Name", "Is", "My", "Name", "Is"]
you'll get [0, 1, 2, 0, 1, 2]
.
Given ["My", "Name", "My", "My", "Name"]
you'll get [0, 1, 0, 0, 1]
.
Hopefully this is more readable and compact answer.
Upvotes: 3