简体   繁体   English

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

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

I have the following Code.我有以下代码。 I have a file with a bunch of data in it and i want to return all occurrences of whatever data i enter into the prompt.我有一个包含一堆数据的文件,我想返回我在提示中输入的任何数据的所有出现。 However the code i have just returns the first occurrence.但是我刚刚返回的代码第一次出现。 i want to know how to return all occurrences.我想知道如何返回所有事件。 This only returns the first one it finds in the list.这只会返回它在列表中找到的第一个。 How would i change this to return all occurrences.我将如何更改它以返回所有事件。 For example if i want it to return all occurrences of PG13 movies that match that rating instead of the first how would i do this?例如,如果我希望它返回与该评级匹配的所有 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"

Your mistake is that you return the flag i, which can be useless in referring to anything.你的错误是你返回了标志 i,它在引用任何东西时都没有用。 Instead, create an empty list and append each matching occurrence.相反,创建一个空列表和 append 每个匹配项。

Hope this helps:)希望这可以帮助:)

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

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