【问题标题】:Iterate through list of objects in Python遍历 Python 中的对象列表
【发布时间】: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.
  • 非常感谢!它有帮助!

标签: python list class


【解决方案1】:

更新(如果最好的书是最赚钱的书):

def best_book(books : List[Book]) -> str:
   return max(books, key=lambda b: b.price * b.sold_units).name

【讨论】:

  • max 函数已经将一个可迭代对象作为参数,不需要列表推导,因为书籍已经是一个可迭代对象。
  • 但它给出了这样的错误:AttributeError: 'int' object has no attribute 'name'
猜你喜欢
  • 2016-12-29
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
  • 2016-11-21
相关资源
最近更新 更多