【问题标题】:Sorting a list of strings in Python [duplicate]在Python中对字符串列表进行排序[重复]
【发布时间】:2012-07-22 03:14:17
【问题描述】:

可能重复:
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。这个lambda 经常和sort 连续出现,这让我很难理解。

我如何获得:

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

到:

Airplane
apple
bicycle
Boat
Car
cow
doctor
Dog

应考虑外语字符(如ä、é、î)。

【问题讨论】:

  • 确定你想要的输出吗? Dog 似乎在该列表中的位置非常错误。
  • @ecatmur 这不是那个问题的重复,这个问题更多的是不区分大小写而不是 unicode
  • @ThiefMaster:谢谢,我更正了。
  • 我认为它 isstackoverflow.com/questions/36139/… 的骗子,因为该问题的公认答案解释了使用相同的语言环境感知和非语言环境感知的不区分大小写的比较技术如我的回答。
  • @ThiefMaster:你是对的。那里接受的答案解决了我的情况。对于 Windows 上的 setlocale,您只需指定类似 b'English_United States'b'German_Germany' 的内容。

标签: python string sorting


【解决方案1】:

使用不区分大小写的比较:

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

这实际上是python wiki about sorting上建议的方式:

从 Python 2.4 开始,list.sort() 和 sorted() 都添加了一个键 参数指定要在每个列表元素上调用的函数 在进行比较之前。

例如,这是一个不区分大小写的字符串比较:

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

【讨论】:

  • 这把Bär放在Bor之后。
【解决方案2】:

这里似乎对该主题进行了很好的概述: http://wiki.python.org/moin/HowTo/Sorting/

向下滚动一个页面到这里;

例如,这是一个不区分大小写的字符串比较:

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

【讨论】:

    猜你喜欢
    • 2016-12-25
    • 1970-01-01
    • 2013-04-15
    • 2018-10-12
    • 2019-05-07
    • 1970-01-01
    • 2016-02-20
    • 2020-05-04
    • 1970-01-01
    相关资源
    最近更新 更多