Logo

Programming-Idioms

History of Idiom 28 > diff from v55 to v56

Edit summary for version 56 by tomdml:
New Python implementation by user [tomdml]

Version 55

2020-02-29, 21:04:17

Version 56

2020-04-29, 09:12:34

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

Imports
from operator import attrgetter
Code
items = sorted(items, key=attrgetter('p')
Comments bubble
We use attrgetter to avoid having to write a lambda. The Operator module contains lots of useful functions that can be passed to higher-order functions.