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?
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With