[Tutor] Python sort with a delimiter

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed May 11 19:22:41 CEST 2005



On Wed, 11 May 2005, Tom Tucker wrote:

> Good morning!  Does Python have a sort function thats supports a delimiter?

Hi Tom,

Not directly, but it's actually not too difficult to get this working.
Python's sort() function can take in an optional "comparison" function, so
we can do something like this:

######
def customCompare(host1, host2):
    return cmp(host1.split('-')[2],
               host2.split('-')[2])
######

and then use this custom comparator by passing it as an additional
argument to sort():

######
somelist.sort(customCompare)
######


The Sorting HOWTO talks about this in more detail:

    http://www.amk.ca/python/howto/sorting/sorting.html


Best of wishes!



More information about the Tutor mailing list