[英]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.