在Python中创建按字母顺序排序的列表的最佳方法是什么?
当前回答
对字符串进行排序的正确方法是:
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)
值得注意的是sorted()函数:
for x in sorted(list):
print x
这将返回一个新的、排序的列表版本,而不改变原始列表。
对字符串进行排序的正确方法是:
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的上下文。
老问题了,但如果你想在不设置locale的情况下进行locale感知排序。LC_ALL你可以通过使用以下答案所建议的PyICU库来实现:
import icu # PyICU
def sorted_strings(strings, locale=None):
if locale is None:
return sorted(strings)
collator = icu.Collator.createInstance(icu.Locale(locale))
return sorted(strings, key=collator.getSortKey)
然后用例如:
new_list = sorted_strings(list_of_strings, "de_DE.utf8")
这对我来说很有效,不需要安装任何区域设置或更改其他系统设置。
(这一点已经在上面的评论中提到了,但我想让它更加突出,因为我自己一开始也没有注意到。)
或者:
names = ['Jasmine', 'Alberto', 'Ross', 'dig-dog']
print ("The solution for this is about this names being sorted:",sorted(names, key=lambda name:name.lower()))