在Python中对字符串列表进行排序

2024-10-03 09:21:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有一个字符串列表list,希望按字母顺序排序。当我调用list.sort()时,列表的第一部分包含以大写字母按字母顺序排序的条目,第二部分包含以小写字母开头的排序条目。就像这样:

Airplane
Boat
Car
Dog
apple
bicycle
cow
doctor

我在谷歌上寻找答案,但没有找到有效的算法。我读到了locale模块和sort参数cmpkey。通常情况下,在与sort的一行中会有这样的lambda,这让我无法更好地理解事情。

我怎么能从:

list = ['Dog', 'bicycle', 'cow', 'doctor', 'Car', 'Boat', 'apple', 'Airplane']

致:

Airplane
apple
bicycle
Boat
Car
cow
doctor
Dog

应考虑到外语的特点(如ä,î,î)。


Tags: inapple排序sortcardolisthow
2条回答

不区分大小写的比较:

>>> sorted(['Dog', 'bicycle', 'cow', 'doctor', 'Car', 'Boat',
        'apple', 'Airplane'], key=str.lower)
['Airplane', 'apple', 'bicycle', 'Boat', 'Car', 'cow', 'doctor', 'Dog']

这实际上是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']

这里似乎对这个主题有一个很好的概述: http://wiki.python.org/moin/HowTo/Sorting/

向下滚动一页到这里

例如,下面是不区分大小写的字符串比较:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)

相关问题 更多 >