在Python中创建按字母顺序排序的列表的最佳方法是什么?
当前回答
请在Python3中使用sorted()函数
items = ["love", "like", "play", "cool", "my"]
sorted(items2)
其他回答
对字符串进行排序的正确方法是:
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'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']
# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']
前面的mylist示例。sort(key=lambda x: x.r lower())将适用于仅限ascii的上下文。
请在Python3中使用sorted()函数
items = ["love", "like", "play", "cool", "my"]
sorted(items2)
或者:
names = ['Jasmine', 'Alberto', 'Ross', 'dig-dog']
print ("The solution for this is about this names being sorted:",sorted(names, key=lambda name:name.lower()))
但是这是如何处理特定于语言的排序规则的呢?它是否考虑了地区因素?
不是,list.sort()是一个泛型排序函数。如果希望根据Unicode规则进行排序,则必须定义一个自定义排序键函数。您可以尝试使用pyuca模块,但我不知道它是否完整。
基本的回答:
mylist = ["b", "C", "A"]
mylist.sort()
这将修改您的原始列表(即就地排序)。在不改变原始列表的情况下,使用sorted()函数获得列表的排序副本:
for x in sorted(mylist):
print x
然而,上面的例子有点幼稚,因为它们没有考虑区域设置,而是执行区分大小写的排序。您可以利用可选参数key来指定自定义排序顺序(使用cmp的替代方法是一种已弃用的解决方案,因为它必须计算多次- key只计算每个元素一次)。
因此,要根据当前的语言环境进行排序,考虑到特定于语言的规则(cmp_to_key是functools中的辅助函数):
sorted(mylist, key=cmp_to_key(locale.strcoll))
最后,如果你需要,你可以为排序指定一个自定义区域:
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子集。对于任何非英语数据,这两个都是错误的:
# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)