I have a list of strings list and want to sort it alphabetically. When I call list.sort() the first part of the list contains the entries starting with upper case letters sorted alphabetically, the second part contains the sorted entries starting with a lower case letter. Like so:
Airplane
Boat
Car
Dog
apple
bicycle
cow
doctor
I googled for an answer but didn't came to a working algorithm. I read about the locale module and the sort parameters cmp and key. Often there was this lambda in a row with sort, which made things not better understandable for me.
How can I get from:
list = ['Dog', 'bicycle', 'cow', 'doctor', 'Car', 'Boat', 'apple', 'Airplane']
to:
Airplane
apple
bicycle
Boat
Car
cow
doctor
Dog
Characters of foreign languages should be taken into account (like ä, é, î).
解决方案
Use case-insensitive comparison:
>>> sorted(['Dog', 'bicycle', 'cow', 'doctor', 'Car', 'Boat',
'apple', 'Airplane'], key=str.lower)
['Airplane', 'apple', 'bicycle', 'Boat', 'Car', 'cow', 'doctor', 'Dog']
This is actually the way suggested on the python wiki about sorting:
Starting with Python 2.4, both list.sort() and sorted() added a key
parameter to specify a function to be called on each list element
prior to making comparisons.
For example, here's a case-insensitive string comparison:
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']