如何从列表中找到最高的浮点数?

How do I find the highest float from a list?

我制作了一个程序,它可以获取您从列表中挑选的电影并告诉您它的导演和评级,它还会告诉您这部电影是否是 highest-rated。我希望程序做它正在做的同样的事情,但它不只是检查标题是否为 5 星,而是检查评级是否高于所有其他浮点数。

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 

在 Python 中,您可以使用 built-in 函数 maxlist(或一般的 iterable 中)获得最大值:

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

在您的情况下,您只需将评级放入列表中:

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

然后求出最高值:

max(ratings)

@Matthias:

建议的这个解决方案更好
max(movieDirectorRatingList, key=lambda x: x[2])

这是一回事,但它可以让你避免初始化无用的list