Home > Net >  How do I check if there is a variable inside a 2d list?
How do I check if there is a variable inside a 2d list?

Time:02-07

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.

CodePudding user response:

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")
    

CodePudding user response:

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])

P.S. I changed a piece of data from your "waterloo" data due to their being two directors being in two different sections in the array.

  •  Tags:  
  • Related