I have a list of objects, that are pre-sorted based on some complex criteria that cannot be easily duplicated with attrgetter, for example. I want to further sort a subset of them alphabetically, if both of them have the property: part_of_subset.
How do I do this without re-defining an alphabetic sort function?
def cmp(a, b):
if a.part_of_subset and b.part_of_subset:
# sort alphabetically -- must I duplicate alphabetic sort code?
return 0
While you can define a comparison function for sorting, it is generally recommended to use a key function. For your application, this key function should return the same value for everything that should be left untouched, and the sort key for the rest. Example
Note that the subset that is sorted will be grouped together to one block after the already sorted elements.
Edited: To get rid of the restriction that
sort_keymay never beNone, and to make the code work in Python 3, I updated the key function. The old version might also have led to strange results in the case that the sort keys are of different types (which does not seem too useful, but anyway).