In Python 3, you can no longer pass a comparison function to the sorted function, but in Python 3.2 you can use functools.cmp_to_key to do the same thing as passing a comparison function to the sorted function. Let's write some samples.
First, let's write a sample that compares and sorts integers by strings.
python
from functools import cmp_to_key
def cmp(a, b):
if a == b: return 0
return -1 if a < b else 1
def cmpstr(a, b):
return cmp(str(a), str(b))
def main():
xs = [4, 90, -9, 12, 42]
print(sorted(xs, key=cmp_to_key(cmpstr)))
main()
This is the execution result.
[-9, 12, 4, 42, 90]
The magnitude comparison result returns -1, 0, or 1. Returns -1 if less, 0 if equal, 1 if greater.
However, in this example only, writing sorted (xs, key = str)
is the same.
Now that I know how to use functools.cmp_to_key
, I'll try the sort I really wanted to do. I have a list of tuples with two elements and I want to sort this list. The comparison method sorts the tuples in ascending order of the second element, and if the second element is equal, in descending order of the first element. The comparison function looks like this:
python
from functools import cmp_to_key
def cmp(a, b):
if a == b: return 0
return -1 if a < b else 1
def cmptuple(a, b):
return cmp(a[1], b[1]) or cmp(b[0], a[0])
def main():
xs = [(4, 90), (-9, 12), (42, 12), (100, 12), (1, 1), (-123, 1)]
print(sorted(xs, key=cmp_to_key(cmptuple)))
main()
This is the execution result.
[(1, 1), (-123, 1), (100, 12), (42, 12), (-9, 12), (4, 90)]
Recommended Posts