@@ -58,28 +58,28 @@ A common pattern is to sort complex objects using some of the object's indices
5858as keys. For example:
5959
6060 >>> student_tuples = [
61- ('john', 'A', 15),
62- ('jane', 'B', 12),
63- ('dave', 'B', 10),
64- ]
61+ ... (' john' , ' A' , 15 ),
62+ ... (' jane' , ' B' , 12 ),
63+ ... (' dave' , ' B' , 10 ),
64+ ... ]
6565 >>> sorted (student_tuples, key = lambda student : student[2 ]) # sort by age
6666 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
6767
6868The same technique works for objects with named attributes. For example:
6969
7070 >>> class Student :
71- def __init__(self, name, grade, age):
72- self.name = name
73- self.grade = grade
74- self.age = age
75- def __repr__(self):
76- return repr((self.name, self.grade, self.age))
71+ ... def __init__ (self , name , grade , age ):
72+ ... self .name = name
73+ ... self .grade = grade
74+ ... self .age = age
75+ ... def __repr__ (self ):
76+ ... return repr ((self .name, self .grade, self .age))
7777
7878 >>> student_objects = [
79- Student('john', 'A', 15),
80- Student('jane', 'B', 12),
81- Student('dave', 'B', 10),
82- ]
79+ ... Student(' john' , ' A' , 15 ),
80+ ... Student(' jane' , ' B' , 12 ),
81+ ... Student(' dave' , ' B' , 10 ),
82+ ... ]
8383 >>> sorted (student_objects, key = lambda student : student.age) # sort by age
8484 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
8585
@@ -208,15 +208,15 @@ return a negative value for less-than, return zero if they are equal, or return
208208a positive value for greater-than. For example, we can do:
209209
210210 >>> def numeric_compare (x , y ):
211- return x - y
212- >>> sorted ([5 , 2 , 4 , 1 , 3 ], cmp = numeric_compare)
211+ ... return x - y
212+ >>> sorted ([5 , 2 , 4 , 1 , 3 ], cmp = numeric_compare) # doctest: +SKIP
213213 [1, 2, 3, 4, 5]
214214
215215Or you can reverse the order of comparison with:
216216
217217 >>> def reverse_numeric (x , y ):
218- return y - x
219- >>> sorted ([5 , 2 , 4 , 1 , 3 ], cmp = reverse_numeric)
218+ ... return y - x
219+ >>> sorted ([5 , 2 , 4 , 1 , 3 ], cmp = reverse_numeric) # doctest: +SKIP
220220 [5, 4, 3, 2, 1]
221221
222222When porting code from Python 2.x to 3.x, the situation can arise when you have
@@ -244,6 +244,12 @@ function. The following wrapper makes that easy to do::
244244
245245To convert to a key function, just wrap the old comparison function:
246246
247+ .. testsetup ::
248+
249+ from functools import cmp_to_key
250+
251+ .. doctest ::
252+
247253 >>> sorted ([5 , 2 , 4 , 1 , 3 ], key = cmp_to_key(reverse_numeric))
248254 [5, 4, 3, 2, 1]
249255
0 commit comments