Sunday 15 March 2015

Python: Sort a list of objects based on their attributes -



Python: Sort a list of objects based on their attributes -

just preface this, i've checked out posts pertaining question , haven't answered mine.

so know how sort list of objects based on attributes in 2 ways:

if attribute string (to alphabetize) if attribute integer (to numerical order)

this list of classes:

mainlist = [ hero( name='sirgoose', classes='fighter', level=150 ), hero( name='conan', classes='barbarian', level=160 ), hero( name='kingarthur', classes='knight', level=170 ) ]

so i'm looking way sort list hero's names sorted in alphabetical order, method level. give thanks you!

sorted, list.sort take optional key parameter. pass key function. homecoming value of function used comparing instead of original value:

>>> collections import namedtuple >>> hero = namedtuple('hero', ['name', 'classes', 'level']) >>> >>> mainlist = [ ... hero(name='sirgoose', classes='fighter', level=150 ), ... hero(name='conan', classes='barbarian', level=160 ), ... hero( name='kingarthur', classes='knight', level=170 ) ... ] >>> sorted(mainlist, key=lambda h: (h.name, h.level)) [hero(name='conan', classes='barbarian', level=160), hero(name='kingarthur', classes='knight', level=170), hero(name='sirgoose', classes='fighter', level=150)]

note: key function used here (lambda) returns tuple. tuples compared item item. if first items same, next items compared, ...

>>> ('sirgoose', 12) < ('barbarian', 160) false >>> ('sirgoose', 12) < ('sirgoose', 160) true

alternative using operator.attrgetter:

>>> import operator >>> sorted(mainlist, key=operator.attrgetter('name', 'level')) [hero(name='conan', classes='barbarian', level=160), hero(name='kingarthur', classes='knight', level=170), hero(name='sirgoose', classes='fighter', level=150)]

python list class sorting

No comments:

Post a Comment