sorting a list numbers stored as strings

Carsten Haese carsten at uniqsys.com
Mon Sep 24 07:39:11 EDT 2007


On Mon, 2007-09-24 at 16:53 +0530, Amit Khemka wrote:
> On 9/24/07, aine_canby at yahoo.com <aine_canby at yahoo.com> wrote:
> > hi,
> >
> > I have the following list -
> >
> > ["1", "11", "2", "22"]
> >
> > how do I sort it like this -
> >
> > ["1", "2", "11", "22"]
> >
> 
> Hi,
> 
> >>> l = ["1", "11", "2", "22"]
> >>> sorted(l, cmp = lambda x, y: cmp(int(x), int(y)))  # provide your
> own compare function !
> >>> l
> ['1', '2', '11', '22']

That interpreter session is a work of fiction, since sorted returns the
sorted list instead of sorting the list in place. Also, it's better
(i.e. more readable and likely faster) to use a sort key function
instead of a comparison function whenever possible. In this case, the
sort key function is particularly trivial:

>>> l = ["1", "11", "2", "22"]
>>> sorted(l, key=int)
['1', '2', '11', '22']

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list