The DSU (Decorate, Sort, Undecorate) idiom originates from Lisp. I first learned it in Perl, where it is called the
Schwartzian Transform (coolest name ever?), named after longtime Perl hacker
Randal L. Schwartz.
I find myself using this same DSU idiom in Python when I need to sort a nested sequence (single level sequence of sequences).
Lets say I have the following list of lists:
seq = [
['a', 1, 5],
['b', 3, 4],
['c', 2, 2],
['d', 4, 3],
['e', 5, 1],
]
... and I want the outer list to contain the inner lists sorted by their last column (in this case, index 2).
How would I do this?
Here is an implementations of the DSU (Decorate, Sort, Undecorate) idiom in a Python function:
def dsu_sort(idx, seq):
for i, e in enumerate(seq):
seq[i] = (e[idx], e)
seq.sort()
for i, e in enumerate(seq):
seq[i] = e[1]
return seq
(Keep in mind that lists in Python are mutable and this will transform your original sequence.)
So applying this to the sequence above like this:
dsu_sort(2, seq)
gives us:
[['e', 5, 1], ['c', 2, 2], ['d', 4, 3], ['b', 3, 4], ['a', 1, 5]]
which is the original sequence, transformed so it is sorted by the last column (index 2).
Randal's original implementation in Perl from 1994:
#!/usr/bin/perl
print
map { $_->[0] }
sort { $a->[1] cmp $b->[1] }
map { [$_, /(\S+)$/] }
<>;