How to use custom functions to sort a list
Custom functions
If you want to have your elements sorted in a specific manner you can define your own comparison function , of the form compare(x,y), which returns a negative number when x < y, a positive number when x > y, and zero when x == y (according to your definition).
You can then supply this as a parameter to sort. The built-in function cmp provides the default behavior:
print cmp(3, 2) # w w w .j av a 2 s . co m
print cmp(99, 100)
print cmp(10, 10)
numbers = [5, 2, 9, 7]
numbers.sort(cmp)
print numbers
The code above generates the following result.
The sort method has two other optional arguments: key and reverse. If you want to use them, you normally specify them by name. The key argument is similar to the cmp argument: You supply a function and it's used in the sorting process.
x = ['java2s.com', 'java', 'ruby', 'C#', 'Python']
x.sort(key=len)
print x
The code above generates the following result.
The other keyword argument, reverse, is simply a truth value indicating whether the list should be sorted in reverse:
x = [4, 6, 2, 1, 7, 9]
x.sort(reverse=True)
print x
The code above generates the following result.
The following code compares lower strings.
caseList = ['d', 'B', 'F', 'A', 'E', 'c']
# w w w . j av a2 s . c om
print caseList
caseList.sort()
print caseList
caseList.sort(key=str.lower)
print caseList
The code above generates the following result.