In Python2, sort has input cmp
to define custom comparizon. However, python3 removed it.
In Pyhton2
>>> def compare(a, b):
... """Comparison that ignores the first letter"""
... return cmp(a[1:], b[1:])
>>> names = ['Adam', 'Donald', 'John']
>>> names.sort(cmp=compare)
>>> names
['Adam', 'John', 'Donald']
In Python3, we can just use key
.
>>> names = ['Adam', 'Donald', 'John']
>>> names.sort(key=lambda x: x[1:])
>>> names
['Adam', 'John', 'Donald']
complex sort:
Sort word count. Data is represented by tuple: (word, count).
1. sort by count in descending order
2. if count is same, sort them with alphebet order of word
>>> l = [('betty', 1), ('a', 1), ('butter', 2)]
>>> def custom_key(x):
... return -x[1], x[0]
...
>>> l.sort(key=custom_key)
>>> l
[('butter', 2), ('a', 1), ('betty', 1)]
How this works?
In comparison, python check first element of tuple. If they are same, compare the next element in tuple. Therefore, sort by count in descending order means first tuple and if count is same means second tuple of element.