sort list doesnt work, key=str still doesnt work

Duncan Booth duncan.booth at invalid.invalid
Tue May 27 04:35:45 EDT 2008


Dan Bishop <danb_83 at yahoo.com> wrote:

> On May 26, 9:46 pm, notnorweg... at yahoo.se wrote:
>> >>> x=sorted([',', ',', 'CHAPTER', 'Emma', 'I', 'I',
>> 'VOLUME', 'Woodhouse', 'clever', 'handsome'], key=str)
>> >>> x
>>
>> [',', ',', 'CHAPTER', 'Emma', 'I', 'I', 'VOLUME', 'Woodhouse',
>> 'clever', 'handsome']
>>
>>
>>
>> what do i need to do?
> 
> x.sort(key=str.upper)

Or another option to consider:

>>> import locale
>>> locale.setlocale(locale.LC_COLLATE, 'en')
'English_United States.1252'
>>> print ', '.join(sorted(['CHAPTER', 'eu', 'Emma', 'I', 'I', 'VOLUME', 
'Woodhouse', 'clever', 'handsome', '\xe9t\xe9'], key=locale.strxfrm))
CHAPTER, clever, Emma, été, eu, handsome, I, I, VOLUME, Woodhouse

Annoyingly strxfrm in Python 2.5 can't cope with unicode so if you go this 
way you need to make sure that the strings are all encoded with the correct 
encoding (which in this example is the 1252 at the end of the string  
returned from setlocale) or define a new key function which applies the 
correct encoding.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list