为什么我的代码从18而不是10打印出来,您能提供任何解决方案吗?
问题内容:
我是python的新手,刚刚在学校开始学习时,我们已经完成了一项任务,它要求您获得一个句子并将其转换为单词列表。
例如:将重新创建为“不问您的国家可以为您做的事?问您可以为您的国家做些什么” [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5]
。
但是该示例并未显示如果您在末尾添加了一个新单词会发生什么情况,并且我的老师要求我在使用该示例时将最后一个单词显示为“ 10”。
例如:“不问您的国家可以为您做的事就问您可以为您的国家马铃薯做些什么”。在我的代码中,它输出为[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5, 18]
我的问题很简单:
为什么代码会精确执行此操作,为什么不将其打印为10而不是18?
您是否可以对我的代码进行任何潜在的修改,并可能向我展示但还要说明其工作原理?
以下是我正在使用的代码。
sentence = input("Please input a sentence that you want to find the locations of all words: ")
words = sentence.split()
print([words.index(s)+1 for s in words])
问题答案:
问题
您期望代码为您提供单词的索引,而无需计算重复的单词,但是您只是在原始字符串中获得了单词索引。
解决方案
首先,您需要在原始字符串中获得 唯一的单词 ,以便 根据需要
获得正确的单词索引。您可以在此处尝试演示。使用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 order
for word in words:
if word not in unique_words:
unique_words.append(word)
#Generate the indexes for the words
indexes = [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]