[英]Indexes of a list Python
I am trying to find how to print the indexes of words in a list in Python.我试图找到如何在 Python 中打印列表中的单词索引。 If the sentence is "Hello world world hello name") I want it to print the list "1, 2, 2, 1, 3")
如果句子是“Hello world world hello name”)我想让它打印列表“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但我仍然需要使用数组获取句子的索引
If you want the index to be the "nth unique word I see in the sentence" then this code would produce this:如果您希望索引成为“我在句子中看到的第 n 个唯一单词”,那么此代码将生成:
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]
结果:
[1, 2, 2, 1, 3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.