在Python中对字符串列表进行排序 [英] Sorting a list of strings in Python

查看:1041
本文介绍了在Python中对字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何在Python中对字符串列表进行排序?
如何在Python中按字母顺序对unicode字符串进行排序?

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

我有一个字符串列表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参数cmpkey的信息.通常,lambdasort连续出现,这使我不容易理解.

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上建议的方式:

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

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

这篇关于在Python中对字符串列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆