在Python中创建按字母顺序排序的列表的最佳方法是什么?
当前回答
很简单: 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)
其他回答
但是这是如何处理特定于语言的排序规则的呢?它是否考虑了地区因素?
不是,list.sort()是一个泛型排序函数。如果希望根据Unicode规则进行排序,则必须定义一个自定义排序键函数。您可以尝试使用pyuca模块,但我不知道它是否完整。
对字符串进行排序的正确方法是:
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的上下文。
设s = "ZWzaAd"
要在字符串上面排序,简单的解决方案是在字符串下面。
print ''.join(sorted(s))
list.sort()
真的就是这么简单:)
或者:
names = ['Jasmine', 'Alberto', 'Ross', 'dig-dog']
print ("The solution for this is about this names being sorted:",sorted(names, key=lambda name:name.lower()))