Logo

Programming-Idioms

  • Perl
  • Python

Idiom #28 Sort by a property

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

from operator import attrgetter
items = sorted(items, key=attrgetter('p'))

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.
items = sorted(items, key=lambda x: x.p)

The lambda expression pulls out the field you want to sort by. If you want to sort in reverse order, add reverse=True to the argument list.
@items = sort { $a->{p} cmp $b->{p} } @items;

sort gives your code block two items to sort: $a and $b. Two operators are commonly used: cmp to sort lexically, and <=> to sort numerically. Swapping the positions of $a and $b reverses the sort direction.
with Ada.Containers.Vectors;
use Ada.Containers;
declare
   function Compare_Function (Left, Right : Item) return Boolean is (Left.P < Right.P);
   
   package Item_Vector_Sorting is new Item_Vectors.Generic_Sorting (Compare_Function);

   use Item_Vector_Sorting;
begin
   Sort (Items);
end;

New implementation...
< >
programming-idioms.org