在Python中创建按字母顺序排序的列表的最佳方法是什么?
当前回答
或者:
names = ['Jasmine', 'Alberto', 'Ross', 'dig-dog']
print ("The solution for this is about this names being sorted:",sorted(names, key=lambda name:name.lower()))
其他回答
l =['abc' , 'cd' , 'xy' , 'ba' , 'dc']
l.sort()
print(l1)
结果
['abc', 'ba', 'cd', 'dc', 'xy']
请在Python3中使用sorted()函数
items = ["love", "like", "play", "cool", "my"]
sorted(items2)
值得注意的是sorted()函数:
for x in sorted(list):
print x
这将返回一个新的、排序的列表版本,而不改变原始列表。
设s = "ZWzaAd"
要在字符串上面排序,简单的解决方案是在字符串下面。
print ''.join(sorted(s))
对字符串进行排序的正确方法是:
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的上下文。