Page 131 - Python for Everybody
P. 131
10.2. COMPARING TUPLES 119 The sort function works the same way. It sorts primarily by first element, but in
the case of a tie, it sorts by second element, and so on. This feature lends itself to a pattern called DSU for
Decorate a sequence by building a list of tuples with one or more sort keys preceding the elements from the sequence,
Sort the list of tuples using the Python built-in sort, and Undecorate by extracting the sorted elements of the sequence.
For example, suppose you have a list of words and you want to sort them from longest to shortest:
txt = 'but soft what light in yonder window breaks' words = txt.split()
t = list()
for word in words:
t.append((len(word), word)) t.sort(reverse=True)
res = list()
for length, word in t:
res.append(word) print(res)
# Code: http://www.py4e.com/code3/soft.py
The first loop builds a list of tuples, where each tuple is a word preceded by its length.
sort compares the first element, length, first, and only considers the second el- ement to break ties. The keyword argument reverse=True tells sort to go in decreasing order.
The second loop traverses the list of tuples and builds a list of words in descending order of length. The four-character words are sorted in reverse alphabetical order, so “what” appears before “soft” in the following list.
The output of the program is as follows:
['yonder', 'window', 'breaks', 'light', 'what',
'soft', 'but', 'in']
Of course the line loses much of its poetic impact when turned into a Python list and sorted in descending word length order.