繁体   English   中英

如何返回列表中匹配的所有匹配项?

[英]How to return all occurrences that match in a list?

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

希望这可以帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM