问题描述
我有一个字符串列表list
,想要按字母顺序对其进行排序.当我调用list.sort()
时,列表的第一部分包含以大写字母开头按字母顺序排序的条目,第二部分包含以小写字母开头的排序条目.像这样:
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
我用Google搜索了一个答案,但没有找到有效的算法.我阅读了有关locale
模块以及sort
参数cmp
和key
的信息.通常,lambda
和sort
连续出现,这使我不容易理解.
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.
我如何获得:
list = ['Dog', 'bicycle', 'cow', 'doctor', 'Car', 'Boat', 'apple', 'Airplane']
收件人:
Airplane
apple
bicycle
Boat
Car
cow
doctor
Dog
应考虑外语字符(例如ä,é,î).
Characters of foreign languages should be taken into account (like ä, é, î).
推荐答案
不区分大小写的比较:
>>> sorted(['Dog', 'bicycle', 'cow', 'doctor', 'Car', 'Boat',
'apple', 'Airplane'], key=str.lower)
['Airplane', 'apple', 'bicycle', 'Boat', 'Car', 'cow', 'doctor', 'Dog']
这实际上是关于分类的Python Wiki上建议的方式:
例如,这是不区分大小写的字符串比较:
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']
这篇关于在Python中对字符串列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!