我有以下代码。我有一个包含一堆数据的文件,我想返回所有出现在提示符下的数据。但是我刚刚返回的代码才第一次出现。我想知道如何返回所有事件。这只会返回它在列表中找到的第一个。我将如何更改以返回所有出现的事件。例如,如果我希望它返回所有符合该等级的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 ""
答案 0 :(得分:0)
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,这对于引用任何内容都可能是无用的。而是创建一个空列表并附加每个匹配项。
希望这会有所帮助:)