【发布时间】:2021-10-14 01:06:32
【问题描述】:
我正在尝试解决 Kaggle 30 天 ML 课程中的以下问题。但是输出是一个空列表,我做错了什么? 提前致谢。
def word_search(doc_list, keyword):
"""
Takes a list of documents (each document is a string) and a keyword.
Returns list of the index values into the original list for all documents
containing the keyword.
Example:
doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
>>> word_search(doc_list, 'casino')
>>> [0]
"""
sentence_lst = []
for sent in doc_list:
l = sent.split(' ')
sentence_lst.append(l)
i_lst = []
for i, sentlist in enumerate(sentence_lst):
for word in sentlist:
if str(word) == str(keyword):
i_lst.append(i)
break
return i_lst
# Check your answer
# q2.check()
word_search(['The Learn Python Challenge Casino', 'They bought a car, and a horse', 'Casinoville?'],'horse')
【问题讨论】:
-
从循环中删除
break。否则,它仅在您查找的单词是句子中的第一个单词时才有效(或将break放在if中)。
标签: python arrays string function