按字典顺序对字符串排序python [英] Sort a string in lexicographic order python
本文介绍了按字典顺序对字符串排序python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按字典顺序将字符串排序为列表
I want to sort a string to a list in lexicographic order as
str='aAaBbcCdE'
到
['A','a','a','B','b','C','c','d','E']
但是sorted()
给我这个输出:
['A','B','C','E','a','a','b','c','d']
如何按字典顺序排序?
推荐答案
当有内置函数可以使用时,请不要使用lambda函数.也不要使用sorted的cmp
参数,因为它已被弃用:
Do not use lambda functions when there's builtin ones for the job. Also never use the cmp
argument of sorted because it's deprecated:
sorted(s, key=str.lower)
或
sorted(s, key=str.upper)
但这可能无法使"A"和"a"保持顺序,所以:
But that may not keep 'A' and 'a' in order, so:
sorted(sorted(s), key=str.upper)
这将并且根据sorted
的性质,对于几乎排序的列表(第二个sorted
),该操作将非常快.
that will and, by the nature of sorted
the operation will be very fast for almost sorted lists (the second sorted
).
这篇关于按字典顺序对字符串排序python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文