Wednesday, August 5, 2009

Python: Customize sorting with a comparator function


Share at Facebook

Many other programming languages, Python does have the comparator facility to sort a list according to your need. You can define a customize compare function which will implement your logic for sorting.

I'm giving few example about sorting first, then customize sorting. Lets talk about simple sorting option at Python.

1) Sort using sorted() function or sort()

## Initial Array
array = [8, 2, 9, 0, 1, 2, 5];
## General sorting
array.sort()
print array

## Another approach
## using function
print sorted(array)


2) Now sorting using custom comparator function.
## custom sort
def comparator(x, y):
return x-y

## Initial Array
array = [8, 2, 9, 0, 1, 2, 5];
array.sort(comparator)
print array


This the very basic of a comparator function. Its just take two objects as parameter, and compare, after that it just return like xy.

3) Now put some logic inside the comparator function for your own purpose.
## custom sort
def comparator(x, y):
## Just a condition for example,
## you can add as many you need.
if(x % 2):
return x
return x-y

## Initial Array
array = [8, 2, 9, 0, 1, 2, 5];
array.sort(comparator)
print array


You can see that I've just put a logic inside my compare function. You just need to build your own comparing mechanism when you'll go to use this type of sorting. Believe me, this kind of things just make your life easier, otherwise you would have to write hundred of lines of codes.




1 comment:

niel de wet said...

Thanks for the nice and simple example. You're just missing one crucial piece of information:

comparator should specify a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument.

See note 8 under this section of the official python documentation.