wiki:python/operator/attrgetter

add, attrgetter, iadd, methodcaller


Python Doc


Examples

Sorting lists

Re: Objekte in Liste speichern?
Re: Liste nach Attributen sortieren...

def sort_datetimes(dates, order=None):
    if order:
        key = lambda d: getattr(d, order)
    else:
        key = None
    return sorted(dates, key=key)

>>> dates = [datetime.datetime(2013, 1, 8), datetime.datetime(2012, 2, 5), datetime.datetime(2011, 3, 9)]
>>> sort_datetimes(dates)
[datetime.datetime(2011, 3, 9, 0, 0),
 datetime.datetime(2012, 2, 5, 0, 0),
 datetime.datetime(2013, 1, 8, 0, 0)]
>>> sort_datetimes(dates, order='day')
[datetime.datetime(2012, 2, 5, 0, 0),
 datetime.datetime(2013, 1, 8, 0, 0),
 datetime.datetime(2011, 3, 9, 0, 0)]

is equivalent to:

def sort_datetimes(dates, order=None):
    key = operator.attrgetter(order) if order else None
    return sorted(dates, key=key)
Last modified 6 years ago Last modified on Oct 15, 2013, 3:51:43 PM