Python:如何应用自定义函数生成出版社书籍嵌套列表并构建字典
Hey there! Let's break down your problem and fix it step by step. First, we'll spot the small bug in your custom function, then cover how to generate the nested book list, build the publisher-to-books dictionary, and clarify how to apply functions to lists in Python.
1. Fixing the book_publisher Function
Your current function has two easy-to-miss issues:
- You're using
nameinstead of the input parameterpublisher(simple typo!) - You're wrapping the pandas Series in an extra list with
return [books], which gives you a list containing a Series instead of a flat list of book names.
Here's the corrected version:
def book_publisher(publisher, df): # Filter rows for the target publisher, extract book names, convert to a clean list books = df.loc[df['publisher_name'] == publisher, 'book_name'].tolist() return books
2. Generating a Nested List of Books
To apply this function to a list of publishers and get your desired [[book1, book2], [book3, book4]] format, you have two straightforward options:
Option 1: List Comprehension (Most Readable)
If you have a list like publishers_list = ["O'Reilly", "Penguin", ...]:
nested_books = [book_publisher(pub, df) for pub in publishers_list]
Option 2: Using map()
You can use Python's built-in map() function, then convert the result to a list:
nested_books = list(map(lambda pub: book_publisher(pub, df), publishers_list))
3. Building the Publisher-to-Books Dictionary
You don't need to generate the nested list first—you can build the dictionary directly with a dictionary comprehension, which is more efficient:
publisher_books_dict = {pub: book_publisher(pub, df) for pub in publishers_list}
Bonus: Faster Pandas-Native Approach
If you're working with pandas, you can skip writing a custom function entirely and use groupby to build the dictionary in one line:
publisher_books_dict = df.groupby('publisher_name')['book_name'].apply(list).to_dict()
This groups your DataFrame by publisher, aggregates book names into lists, then converts the result to a dictionary—way cleaner and faster for large datasets!
4. Applying Functions to Lists in Python
Note: Python 3 removed the built-in apply() function. For applying a function to every item in a list, the most common Pythonic approaches are:
- List Comprehension: As shown above, it's readable and flexible for most cases.
map(): Great for simple operations, but remember to convert the map object to a list.functools.partial(for multi-argument functions): If you want to fix one argument (like yourdf) and apply the function to a list of the other argument:from functools import partial # Fix the df parameter so we only need to pass the publisher name get_books_for_publisher = partial(book_publisher, df=df) nested_books = list(map(get_books_for_publisher, publishers_list))
内容的提问来源于stack exchange,提问作者Oct

