3

Possible Duplicate:
How do I sort a list of strings in Python?
How do I sort unicode strings alphabetically in Python?

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 ä, é, î).

Community
  • 1
  • 1
rynd
  • 1,865
  • 5
  • 22
  • 24
  • 2
    Are you **sure** about the output you want? `Dog` seems to be at a very wrong place in that list. – ThiefMaster Jul 23 '12 at 20:38
  • @ecatmur this is not a duplicate of that question, this one is more about case-insensitivity than unicode – Daniel DiPaolo Jul 23 '12 at 20:40
  • 1
    I think it *is* a dupe of http://stackoverflow.com/questions/36139/how-do-i-sort-a-list-of-strings-in-python though since the accepted answer on that question explains both locale-aware and non-locale-aware case insensitive comparisons using the same technique as in my answer. – ThiefMaster Jul 23 '12 at 20:46
  • @ThiefMaster: You're right. The accepted answer there solves my case. For `setlocale` on Windows you just have to specify something like `b'English_United States'` or `b'German_Germany'`. – rynd Jul 23 '12 at 23:40

2 Answers2

10

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']
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
4

There seems to be a good overview of that topic here: http://wiki.python.org/moin/HowTo/Sorting/

Scroll down about a page to here;

For example, here's a case-insensitive string comparison:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Oliver Gray
  • 874
  • 6
  • 17