简体   繁体   中英

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?

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. Instead, create an empty list and append each matching occurrence.

Hope this helps:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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