You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中遍历对象列表查找销量最高书籍名称的实现方法

原代码可修正问题

  • Book类的__init__方法缩进错误,应与类的文档字符串保持同级缩进
  • 创建书籍实例的循环使用range(10),但titles、authors等列表仅包含3个元素,运行会触发索引越界错误,需改为range(len(titles))
  • 原有遍历逻辑错误:比较对象误用了price属性而非需求要求的sold_units,且max()无法直接作用于单个数字,也没有存储最大值对应的书名信息

功能实现

手动for循环实现(明确遍历过程)

from typing import List

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.
    """
    max_sold = -1
    best_book_name = ""
    for book in books:
        if book.sold_units > max_sold:
            max_sold = book.sold_units
            best_book_name = book.name
    return best_book_name

# 测试代码
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(len(titles)):
    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)

print(best_book(books)) # 输出:The Lion, the Witch and the Wardrobe

简化实现(用Python内置max函数)

可以直接通过key参数指定比较sold_units属性,一行即可完成逻辑:

def best_book(books : List[Book]) -> str:
    """Returns the name of the book that has sold more units.
    """
    return max(books, key=lambda book: book.sold_units).name

如果列表存在多本销量相同的最高书籍,上述两种方法都会返回第一本出现的最高销量书籍名称。


内容的提问来源于stack exchange,提问作者hello_w

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 12:09:05