[Tutor] sort list alphabetically

John Fouhy john at fouhy.net
Thu Nov 24 01:19:54 CET 2005


On 24/11/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
> The files that start with uppercase come first because of the way those
> strings compare to lowercase strings.  If we want a case-insensitive sort,
> we can do something like this:
>
> ######
> >>> def case_insensitive_cmp(a, b):
> ...     return cmp(a.upper(), b.upper())
> ...
> >>> files.sort(case_insensitive_cmp)
> >>> files
[...]
> ######

In python2.4, you can also use the key= keyword argument:

###
def toUpper(s):
 return s.upper()
files.sort(key=toUpper)
###

This is more efficient, I believe, because the key function is only
called once for each element, whereas cmp is called more than once.

(we could use string.upper here instead of defining our own, but
string.upper is deprecated these days...)

--
John.


More information about the Tutor mailing list