问题
您期望代码为您提供单词的索引,而无需计算重复的单词,但是您只是在原始字符串中获得了单词索引。
解决方案
首先,您需要在原始字符串中获得 唯一的单词 ,以便 根据需要
获得正确的单词索引。您可以在此处尝试演示。使用
Potato多余的单词,它返回索引
10 而不是 18 ,因为它在唯一列表中而不是原始列表中查找索引。
string = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY POTATO'words = string.split()unique_words = []#Remove the duplicates while preserving orderfor word in words: if word not in unique_words: unique_words.append(word)#Generate the indexes for the wordsindexes = [unique_words.index(word)+1 for word in words]print(indexes)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5, 10]



