在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")
magic_organize_function是否存在?否则,会是什么?
答案 0 :(得分:1)
按作者排序是一种方式:
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
您还可以使用itertools.groupby
很好地按作者分组:
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
。