2016-12-20 33 views
0

在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") 

的magic_organize_function存在嗎?否則,它會是什麼?

+0

那麼你想按作者分組和排序嗎? – birryree

+3

Python中的sorted()函數採用'key'參數。它用於指定希望列表排序的_how_。在你的情況下,你想按照'books'列表中每個元素的'author'屬性進行排序:'sorted_by_autor = sorted(books,lambda book:book.author)'' –

+0

FWIW'''是多餘的。他們什麼都不做。 –

回答

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

+0

這正是我所期待的。非常感謝! –

相關問題