python - 如何返回列表中匹配的所有匹配项?
问题描述
我有以下代码。我有一个包含一堆数据的文件,我想返回我在提示中输入的任何数据的所有出现。但是我刚刚返回的代码第一次出现。我想知道如何返回所有事件。这只会返回它在列表中找到的第一个。我将如何更改它以返回所有事件。例如,如果我希望它返回与该评级匹配的所有 PG13 电影,而不是第一个,我将如何做到这一点?
def getRating(titlesList,ratingList,ratingname):
#This function will take the ratings,films and userrating parameters
#It will look through the ratings list to search for the specific rating
#the user chooses
#It then returns a list of all the films of a certain rating
i = 0
found = 0
while i < len(ratingList) and found == 0:
if ratingname == ratingList[i]:
found = 1
else:
i = i + 1
if found == 1:
return i
else:
return ""
解决方案
def getRating(titlesList,ratingList,ratingname):
#This function will take the ratings,films and userrating parameters
#It will look through the ratings list to search for the specific rating
#the user chooses
#It then returns a list of all the films of a certain rating
i = 0
found = 0
listOfFilms = []
while i < len(ratingList):
if ratingname == ratingList[i]:
found = 1
listOfFilms.append(ratingList[i])
else:
i += 1
if found == 1:
return listOfFilms
else:
return "There's no occurrences"
你的错误是你返回了标志 i,它在引用任何东西时都没有用。相反,创建一个空列表并附加每个匹配的事件。
希望这可以帮助 :)
推荐阅读
- adfs - ADFS - 客户端凭据授予流程 - 资源服务器不验证 jwt
- javascript - 如何将 jsPDF 中的 PDF 文件保存在 Javascript 中的服务器上?
- python - numpy中不同形状的高效矩阵乘法
- clojure - 函数不返回(Clojure)
- ember.js - EmberJs Promises - 现在让 .map() 或 .forEach() 异步?
- c++ - 渲染文档无法启动我的应用程序
- javascript - 在 Vue-CLI 3 项目的 i18n 标签中添加 yaml-loader
- python - 创建 Python Dashboard 的简单方法
- amazon-web-services - 使用当前版本的 AWS EMR(使用 1.5.0)运行 Flink 1.5.1
- css - 我想通过css在浏览器中禁用输入类型=“日期”的本机日历