python - 该代码显示一个字符串列表包含一个特定的单词。请告诉我为什么我的代码没有给出正确的答案?
问题描述
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
解决方案
此函数将返回包含字符串项目中关键字的项目索引的列表。
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]
推荐阅读
- java - 文件未正确上传
- ansible - 如何在 Ansible mongodb_user 模块中指定 CA 证书
- pandas - 调整和重新索引漂移时间索引数据帧
- node.js - NestJS 视图未添加到 Dist
- swift - 数组中的解析值未显示在表格视图中
- swift - 无法理解如何使用 url-scheme
- flutter - 如何在 Flutter 中更新内部小部件
- openapi - 如何从 OpenAPI 3.0 中的数组模式中引用另一个模式?
- apache-spark - 如何将结构数组转换为多列?
- solr - Apache Nutch REST API 从运行 Nutch 的服务器检索数据?