Home > Blockchain >  How do I find the highest float from a list?
How do I find the highest float from a list?

Time:02-10

I have made a program that gets a movie you pick from a list and tells you its directors and rating it also tells you if a movie is the highest-rated. I want the program to do the same thing it is doing but instead of just checking if the title is 5 stars, it checks if the rating is higher than all the other floats.

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. and Sergei Bondarchuk", 4.0],
  ["Iron Man", "Jon Favreau", 5.0],
  ["Harry Potter", "Chris Columbus", 4.1],
  ["Percy Jackson", "Thor Freudenthal and Chris Columbus", 3.8],
  ["John Wick", "Chad Stahelski", 4.9],
  ["Avengers:Civil War", "Joe Russo and Anthony Russo" , 2.2]
  #Made a 2d list called movieDirectorRatingList which stores the movies with their name, director and rating
]

movieSelection = input("What movie would you like to know about?\nMunich: The Edge of War, Avengers:Endgame, Tombstone, Waterloo, Iron Man, Harry Potter, Percy Jackson, John Wick or Avengers:Civil War\n")
#Asks the user what movie they would like to know about and stores it in a variable called movieSelection
  
for movie in movieDirectorRatingList:
  #divides the 2d list into smaller sections each known as movie
  title, director, rating = movie 
  #Unpacks each of the movie bits from movieDirectorRatingList and explains what each of the variables within it are in the order of title, director and lastly, rating
  if movieSelection in movie and rating != 5.0:
    print(f"{movieSelection} directed by {director}: {rating}" )
    #prints the movie selec with it's director and rating
    break 
    #stops the program
  elif movieSelection in movie and rating == 5.0:
    print(f"{movieSelection} directed by {director}: {rating}" )
    #prints the movie selec with it's director and rating
    print("This is one of the highest rated movies")
    break
    #stops the program
else:
    print("Movie selection not found")     
    #prints that the movie selection wasn't found 

CodePudding user response:

In Python you can get the highest value in a list (or in an iterable in general) with the built-in function max:

>>> l = [1, 2, 4, 3]
>>> max(l)
4

In your case you just have to put the ratings into a list:

ratings = [x[2] for x in movieDirectorRatingList]

and then find the highest value:

max(ratings)

An even better solution would be this one suggested by @Matthias:

max(movieDirectorRatingList, key=lambda x: x[2])

This is the same thing, but it allows you to avoid initializing a useless list.

  • Related