简体   繁体   English

如何检查二维列表中是否有变量?

[英]How do I check if there is a variable inside a 2d list?

I am trying to make code that asks what movie you would like to know about and gives you the movie + the director + a rating.我正在尝试编写代码,询问您想了解哪部电影,并为您提供电影 + 导演 + 评级。

movieDirectorRatingList = [
    ["Munich: The Edge of War", "Christian Schwochow", "4.1"],
    ["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", "4.8"],
    ["Tombstone", "Cosmatos and Kevin Jarre", "4.1"],
    ["Waterloo", "George P.","Sergei Bondarchuk", "4.0"],
    ["Iron Man", "Jon Favreau", "4.9"]
]

movieSelection = input("What movie would you like to know about?")

if movieSelection in movieDirectorRatingList:
    movieLocation = movieDirectorRatingList.count(movieSelection) - 1 
    print(f"{movieSelection} directed by {movieDirectorRatingList[movieLocation][2]}{movieDirectorRatingList[movieLocation][3]}" )

elif movieSelection not in movieDirectorRatingList:
    print("Movie not in list")

else:
    print("An unexpected error has occured")

I managed to have it working when I used 1-dimensional lists, but when I use 2 dimensional ones it says the Movie isn't in the list.当我使用一维列表时,我设法让它工作,但是当我使用二维列表时,它说电影不在列表中。 Thank you in advance for any help.预先感谢您的任何帮助。

You need to iterate through each list:您需要遍历每个列表:

for movie in movieDirectorRatingList:
    title, director, rating = movie # let's unpack these here
    if movieSelection in movie:
        print(f"{movieSelection} directed by {director} {rating}" )
        break # found the movie
else:
    print("Movie selection not found")
    

I used your code and reformatted it and made this.我使用了你的代码并重新格式化并制作了这个。 It does what I believe you want, but slightly simpler.它做我相信你想要的,但稍微简单一些。

mdrl = [
    ["Munich: The Edge of War", "Christian Schwochow", "4.1"],
    ["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", "4.8"],
    ["Tombstone", "Cosmatos and Kevin Jarre", "4.1"],
    ["Waterloo", "George P. and Sergei Bondarchuk", "4.0"],
    ["Iron Man", "Jon Favreau", "4.9"]
]

movieChoice = input("Which movie would you like to get data from?: ")

for i in range(len(mdrl)):
    if mdrl[i][0] == movieChoice:
        print(mdrl[i][0], "Was directed by", mdrl[i][1], "and had a rating of ", mdrl[i][2])

PS I changed a piece of data from your "waterloo" data due to their being two directors being in two different sections in the array. PS 我从你的“滑铁卢”数据中更改了一段数据,因为它们是两个导演,位于数组的两个不同部分。

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

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