问题描述
在Python中创建按字母顺序排序的列表的最佳方法是什么?
What is the best way of creating an alphabetically sorted list in Python?
推荐答案
基本答案:
mylist = ["b", "C", "A"]
mylist.sort()
这会修改您的原始列表(即就地排序).要获得列表的排序副本而不更改原始列表,请使用 sorted()
函数:
This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the sorted()
function:
for x in sorted(mylist):
print x
但是,上面的示例有些天真,因为它们没有考虑区域设置,而是执行区分大小写的排序.您可以利用可选参数key
来指定自定义排序顺序(使用cmp
的替代方法是不建议使用的解决方案,因为必须对其进行多次评估-key
每个元素仅计算一次).
However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter key
to specify custom sorting order (the alternative, using cmp
, is a deprecated solution, as it has to be evaluated multiple times - key
is only computed once per element).
因此,要根据当前语言环境进行排序,并考虑到特定于语言的规则( cmp_to_key
是functools的帮助函数):
So, to sort according to the current locale, taking language-specific rules into account (cmp_to_key
is a helper function from functools):
sorted(mylist, key=cmp_to_key(locale.strcoll))
最后,如果需要,您可以指定自定义语言环境进行排序:
And finally, if you need, you can specify a custom locale for sorting:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'),
key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']
最后一点:您将看到使用lower()
方法的不区分大小写的排序示例-这些是不正确的,因为它们仅适用于ASCII字符集.对于任何非英语数据,这两个都是错误的:
Last note: you will see examples of case-insensitive sorting which use the lower()
method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:
# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)
这篇关于如何对字符串列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!