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

Having an object array in python, how can I classify its elements by an attribute?

在python中,是否有一个按属性对对象数组进行分类和排序的函数?

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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")

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


按作者排序是一种方法:

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

输出:

1
2
3
4
5
6
7
8
George R.R Martin
George R.R Martin
J.k Rowling
J.k Rowling
J.k Rowling
Suzanne Collins
Suzanne Collins
Suzanne Collins

您还可以使用itertools.groupby按作者分组:

1
2
3
4
5
6
7
8
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)

输出:

1
2
3
4
5
6
7
8
9
10
11
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

注:您需要将排序后的sorted_by_author送入groupby