我试图找到如何在Python中打印列表中的单词索引。如果句子是“Hello world world hello name”,我希望它打印列表“1,2,2,1,3”)
我删除了所有重复的单词:
sentence = input("Enter").lower()
words = sentence.split()
counts = []
for word in words:
if word not in counts:
counts.append(word)
print(counts)
但是我还需要使用数组
来获取句子的索引答案 0 :(得分:0)
如果你希望索引是我在句子中看到的" 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(' ')]
结果:[1, 2, 2, 1, 3]