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存在嗎?否則,它會是什麼?
那麼你想按作者分組和排序嗎? – birryree
Python中的sorted()函數採用'key'參數。它用於指定希望列表排序的_how_。在你的情況下,你想按照'books'列表中每個元素的'author'屬性進行排序:'sorted_by_autor = sorted(books,lambda book:book.author)'' –
FWIW'''是多餘的。他們什麼都不做。 –