在python中有一个对象数组,如何通过属性对其元素进行分类?

2024-06-13 09:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,是否有一个函数可以按属性对对象数组进行分类和排序?你知道吗

示例:

class Book:
    """A Book class"""
    def __init__(self,name,author,year):
        self.name = name
        self.author = author
        self.year = year

hp1 = Book("Harry Potter and the Philosopher's stone","J.k Rowling",1997)
hp2 = Book("Harry Potter and the chamber of secretse","J.k Rowling",1998)
hp3 = Book("Harry Potter and the Prisioner of Azkaban","J.k Rowling",1999)

#asoiaf stands for A Song of Ice and Fire
asoiaf1 = Book("A Game of Thrones","George R.R Martin",1996)
asoiaf2 = Book("A Clash of Kings","George R.R Martin",1998)

hg1 = Book("The Hunger Games","Suzanne Collins",2008)
hg2 = Book("Catching Fire","Suzanne Collins",2009)
hg3 = Book("Mockingjaye","Suzanne Collins",2010);

books = [hp3,asoiaf1,hp1,hg1,hg2,hp2,asoiaf2,hg3]
#disordered on purpose

organized_by_autor = magic_organize_function(books,"author")

魔法组织功能存在吗?否则,会是什么?你知道吗


Tags: andofthenameselfyearclassauthor
1条回答
网友
1楼 · 发布于 2024-06-13 09:35:17

按作者排序是一种方法:

sorted_by_author = sorted(books, key=lambda x: x.author)
for book in sorted_by_author:
    print(book.author)

输出:

George R.R Martin
George R.R Martin
J.k Rowling
J.k Rowling
J.k Rowling
Suzanne Collins
Suzanne Collins
Suzanne Collins

您还可以使用^{}按作者很好地分组:

from itertools import groupby

organized_by_author = groupby(sorted_by_author, key=lambda x: x.author)

for author, book_from_author in organized_by_author:
    print(author)
    for book in book_from_author:
        print('    ', book.name)

输出:

George R.R Martin
     A Game of Thrones
     A Clash of Kings
J.k Rowling
     Harry Potter and the Prisioner of Azkaban
     Harry Potter and the Philosopher's stone
     Harry Potter and the chamber of secretse
Suzanne Collins
     The Hunger Games
     Catching Fire
     Mockingjaye

注意:您需要向groupby输入排序后的sorted_by_author。你知道吗

相关问题 更多 >