首页 > 解决方案 > 如何返回列表中匹配的所有匹配项?

问题描述

我有以下代码。我有一个包含一堆数据的文件,我想返回我在提示中输入的任何数据的所有出现。但是我刚刚返回的代码第一次出现。我想知道如何返回所有事件。这只会返回它在列表中找到的第一个。我将如何更改它以返回所有事件。例如,如果我希望它返回与该评级匹配的所有 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 ""

标签: python

解决方案


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,它在引用任何东西时都没有用。相反,创建一个空列表并附加每个匹配的事件。

希望这可以帮助 :)


推荐阅读