【发布时间】:2021-11-21 13:48:40
【问题描述】:
class Book:
"""Represents information about books.
attributes: name, author, price, sold_units
"""
def __init__(self):
self.name : str = ""
self.author : str = ""
self.price : float = 0.0
self.sold_units : int= 0
def best_book(books : List[Book]) -> str:
"""Returns the name of the book that has sold more units.
"""
result = ""
......
return result
titles = ['Think and Grow Rich', 'The Da Vinci Code', 'The Lion, the Witch and the Wardrobe']
authors = ['Napoleon Hill', 'Dan Brown', 'C.S. Lewis']
prices = [5, 5, 5]
sold_units_per_book = [10, 20, 30]
books = []
for i in range(10):
book = Book()
book.name = titles[i]
book.author = authors[i]
book.price = prices[i]
book.sold_units = sold_units_per_book[i]
books.append(book)
best_book(books)
我有对象列表 - 书籍,我需要在我的函数 best_book 中返回已售出更多单位的书籍的名称。
我不知道如何使用 foo 循环遍历对象列表,找到最大值并同时返回书名。 也许是这样的:
for obj in books:
max(obj.price)
也许有人知道怎么做?
【问题讨论】:
-
max(books, key=lambda b: b.price)… -
问题是问“卖得更多的书的名字”,而不是最高价格。所以:
result = max(books, key=lambda book: book.sold_units).name. -
非常感谢!它有帮助!