首页 > 解决方案 > 该代码显示一个字符串列表包含一个特定的单词。请告诉我为什么我的代码没有给出正确的答案?

问题描述

def word_search(doc_list, keyword): """ 获取文档列表(每个文档是一个字符串)和一个关键字。将索引值列表返回到包含该关键字的所有文档的原始列表中。

Example:
doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
>>> word_search(doc_list, 'casino')
>>> [0]
"""

for i,doc in enumerate(doc_list):
    l=[i for j in doc.split() if j.rstrip('.,').lower()==keyword.lower()]

return l

标签: pythonstringlistsearchlist-comprehension

解决方案


此函数将返回包含字符串项目中关键字的项目索引的列表。

doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
def word_search(doc_list, keyword):
    return [i for i, v in enumerate(doc_list) if v.lower().find(keyword.lower()) > -1]
word_search(doc_list, 'casino')

返回索引

[0, 2]

推荐阅读