Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

Indexes of a list Python

I am trying to find how to print the indexes of words in a list in Python. If the sentence is "Hello world world hello name") I want it to print the list "1, 2, 2, 1, 3")

I removed all duplicates of words with this:

sentence = input("Enter").lower()
words = sentence.split()
counts = []
for word in words:
    if word not in counts:
       counts.append(word)
print(counts)

But I need to still get indexes of the sentence using an array

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want the index to be the "nth unique word I see in the sentence" then this code would produce this:

sentence = "Hello world world hello name".lower()
first_occurence = dict()
for pos, word in enumerate(sentence.split(" ")):
    if word not in first_occurence:
        first_occurence[word] = len(first_occurence)

res = [first_occurence[word] + 1 for word in sentence.split(' ')]

result: [1, 2, 2, 1, 3]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...