Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement a Schwartzian Transform in Python?

In Perl I sometimes use the Schwartzian Transform to efficiently sort complex arrays:

@sorted = map  { $_->[0] }  # sort by word length
          sort { $a->[1] <=> $b->[1] } # use numeric comparison
          map  { [$_, length($_)] }    # calculate the length of the string
               @unsorted;

How to implement this transform in Python?

like image 601
planetp Avatar asked Jun 25 '17 19:06

planetp


1 Answers

You don't need to. Python has this feature built in, and in fact Python 3 removed C-style custom comparisons because this is so much better in the vast majority of cases.

To sort by word length:

unsorted.sort(key=lambda item: len(item))

Or, because len is already an unary function:

unsorted.sort(key=len)

This also works with the built-in sorted function.

If you want to sort on multiple criteria, you can take advantage of the fact that tuples sort lexicographically:

# sort by word length, then alphabetically in case of a tie
unsorted.sort(key=lambda item: (len(item), item)))
like image 70
Eevee Avatar answered Oct 19 '22 23:10

Eevee