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


当前回答

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

结果

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

其他回答

设s = "ZWzaAd"

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

print ''.join(sorted(s))

值得注意的是sorted()函数:

for x in sorted(list):
    print x

这将返回一个新的、排序的列表版本,而不改变原始列表。

list.sort()

真的就是这么简单:)

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