[英]Trying to print something if it is NOT in a list
movies = [[1939, 'Gone With the Wind', 'drama'],
[1943, 'Casablanca', 'drama'],
[1961, 'West Side Story', 'musical'],
[1965, 'The Sound of Music', 'musical'],
[1969, 'Midnight Cowboy', 'drama'],
[1972, 'The Godfather', 'drama'],
[1973, 'The Sting', 'comedy'],
[1977, 'Annie Hall', 'comedy'],
[1981, 'Chariots of Fire', 'drama'],
[1982, 'Gandhi', 'historical'],
[1984, 'Amadeus', 'historical'],
[1986, 'Platoon', 'action'],
[1988, 'Rain Man', 'drama'],
[1990, 'Dances with Wolves', 'western'],
[1991, 'The Silence of the Lambs', 'drama'],
[1992, 'Unforgiven', 'western'],
[1993, 'Schindler s List', 'historical'],
[1994, 'Forrest Gump', 'comedy'],
[1995, 'Braveheart', 'historical'],
[1997, 'Titanic', 'historical'],
[1998, 'Shakespeare in Love', 'comedy'],
[2001, 'A Beautiful Mind', 'historical'],
[2002, 'Chicago', 'musical'],
[2009, 'The Hurt Locker', 'action'],
[2010, 'The Kings Speech', 'historical'],
[2011, 'The Artist', 'comedy'],
[2012, 'Argo', 'historical'],
[2013, '12 Years a Slave', 'drama'],
[2014, 'Birdman', 'comedy'],
[2016, 'Moonlight', 'drama'],
[2017, 'The Shape of Water', 'fantasy'],
[2018, 'Green Book', 'drama'],
[2019, 'Parasite', 'drama'],
[2020, 'Nomadland', 'drama'] ]
category = input("Enter a category: ")
for x in movies:
if category in x[2]:
print("\n",x[1])
if category not in x:
print("No matches")
这是我程序的一小段,但如果类别不在列表中,我想打印“不匹配”,但即使类别在列表中,它也会打印它。 仅当输入的类别不在列表中时才有效。 我已经为此工作了很长时间,但在任何地方都找不到答案。
据我了解,当您输入action
时,您会得到电影列表,然后是No matches
,如下所示:
Enter a category: action
Platoon
The Hurt Locker
No matches
所以,如果你不想在找到电影时在最后显示No matches
,那么你可以使用这个:
flag = 0
category = input("Enter a category: ")
for x in movies:
if category in x:
flag = 1
print("\n",x[1])
if flag == 0:
print("No matches")
如果找到任何匹配项,那么我们会将标志设置为 1 并仅在未找到匹配项时打印No matches
..
有一些可能适用的修复和优化:
我认为您想从列表中提取所有具有匹配category
的标题,即如果我输入drama
,它将打印所有带有 drama 的电影。 所以你只需要比较,不需要重新检查in
,因为不必要的检查年份和电影标题的成本更高。 在您问题中显示的数据中,每部电影只有一个类别,因此可以应用此优化。
您只需要一个标志来指示该类别是否确实存在。
category = input("Enter a category: ")
exist = False # Define the flag
for x in movies:
if category == x[2]: # Check if the movie's category is same as the user input
print("\n",x[1])
exist = True # Change if found any
if not exist:
print("No Matches!")
处理这个问题的最简单方法似乎是创建一个包含所有匹配电影片名的列表。 如果该列表为空,则打印未找到:
query = input("Enter a category: ")
found = [title for date, title, category in movies if category == query]
if found:
print('\n'.join(found))
else:
print("Not found")
这将像:
> Enter a category: musical
West Side Story
The Sound of Music
Chicago
> Enter a category: scifi
Not found
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.