Sorting a list of strings in Python [duplicate]

谁都会走 提交于 2020-01-21 12:08:45

问题


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


回答1:


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']



回答2:


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)


来源:https://stackoverflow.com/questions/11620088/sorting-a-list-of-strings-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!