在Python中创建按字母顺序排序的列表的最佳方法是什么?


当前回答

老问题了,但如果你想在不设置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")

这对我来说很有效,不需要安装任何区域设置或更改其他系统设置。

(这一点已经在上面的评论中提到了,但我想让它更加突出,因为我自己一开始也没有注意到。)

其他回答

请在Python3中使用sorted()函数

items = ["love", "like", "play", "cool", "my"]
sorted(items2)

很简单: https://trinket.io/library/trinkets/5db81676e4

scores = '54 - Alice,35 - Bob,27 - Carol,27 - Chuck,05 - Craig,30 - Dan,27 - Erin,77 - Eve,14 - Fay,20 - Frank,48 - Grace,61 - Heidi,03 - Judy,28 - Mallory,05 - Olivia,44 - Oscar,34 - Peggy,30 - Sybil,82 - Trent,75 - Trudy,92 - Victor,37 - Walter'

Scores = Scores .split(',') 对于已排序的x(分数): 打印(x)

或者:

names = ['Jasmine', 'Alberto', 'Ross', 'dig-dog']
print ("The solution for this is about this names being sorted:",sorted(names, key=lambda name:name.lower()))

老问题了,但如果你想在不设置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")

这对我来说很有效,不需要安装任何区域设置或更改其他系统设置。

(这一点已经在上面的评论中提到了,但我想让它更加突出,因为我自己一开始也没有注意到。)

list.sort()

真的就是这么简单:)