Sorting strings.

Geoff Talvola gtalvola at nameconnector.com
Thu Feb 8 09:58:05 EST 2001


Christian Tismer wrote:

> Gaute B Strokkenes wrote:
>
> > The problem with this approach is that string comparison doesn't quite
> > have the behaviour that I would like.  For instance, I'd like numbers
> > to come after letters, and I'd like to be case insensitive.  Is there
> > a reasonably clean way to do this?
>
> There are several ways. As someone else pointed out, you can of
> course make your cmp function as sophisticated as necessary.
>
> Slightly less powerful, but reasonably faster is to calculate
> a suitable key field (which might be a tuple) and do the
> sorting on that, without supplying an extra cmp function.
>

Here's a utility function that makes it easy to sort by providing
a function that constructs a sort key:

def sortUsingKeyFunc(l, keyfunc):
    l = [(keyfunc(x), x) for x in l]
    l.sort()
    return [y for x,y in l]

To use it, simply provide a "keyfunc" that constructs a sort key
for the items in the list.  For example, to sort a list of strings
alphabetically:

>>> l = ['E', 'd', 'A', 'b', 'C']
>>> import string
>>> sortUsingKeyFunc(l, string.upper)
['A', 'b', 'C', 'd', 'E']

Or to sort a list of dictionaries on "name" case-insensitively,
and secondarily on "value":

>>> l = [{'name':'AAA', 'value':5},
...      {'name':'aaa', 'value':4},
...      {'name':'AAA', 'value':3},
...      {'name':'bbb', 'value':2}]
>>> def keyfunc(d):
...     return d['name'].upper(), d['value']
...
>>> from pprint import pprint
>>> pprint(sortUsingKeyFunc(l, keyfunc))
[{'value': 3, 'name': 'AAA'},
 {'value': 4, 'name': 'aaa'},
 {'value': 5, 'name': 'AAA'},
 {'value': 2, 'name': 'bbb'}]

Note that sortUsingKeyFunc returns a new list -- the original list is unmodified.

--


- Geoff Talvola
  Parlance Corporation
  gtalvola at NameConnector.com





More information about the Python-list mailing list