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


当前回答

设s = "ZWzaAd"

要在字符串上面排序,简单的解决方案是在字符串下面。

print ''.join(sorted(s))

其他回答

l =['abc' , 'cd' , 'xy' , 'ba' , 'dc']
l.sort()
print(l1)

结果

['abc', 'ba', 'cd', 'dc', 'xy']

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

请在Python3中使用sorted()函数

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

设s = "ZWzaAd"

要在字符串上面排序,简单的解决方案是在字符串下面。

print ''.join(sorted(s))