开发者

Sort a string in lexicographic order python

开发者 https://www.devze.com 2023-04-04 11:52 出处:网络
I want to sort a string to a list in lexicographic order as str=\'aAaBbcCdE\' to [\'A\',\'a\',\'a\',\'B\',\'b\',\'C\',\'c\',\'d\',\'E\']

I want to sort a string to a list in lexicographic order as

str='aAaBbcCdE'

to

['A','a','a','B','b','C','c','d','E']

but sorted() gives me this output:

['A','B','C','E','a','a','b','c','d']

How开发者_JS百科 can I sort lexicographically?


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)

or

sorted(s, key=str.upper)

But that may not keep 'A' and 'a' in order, so:

sorted(sorted(s), key=str.upper)

that will and, by the nature of sorted the operation will be very fast for almost sorted lists (the second sorted).


You could use a 2-tuple for the key:

text='aAaBbcCdE'
sorted(text, key=lambda x: (str.lower(x), x))
# ['A', 'a', 'a', 'B', 'b', 'C', 'c', 'd', 'E']

The first element in the tuple, str.lower(x) is the primary key (making a come before B), while x itself breaks ties (making A come before a).


cmp was the old way of doing this, now deprecated, but for posterity:

s='aAaBbcCdE'
sorted(s, lambda x,y: cmp(x.lower(), y.lower()) or cmp(x,y))


data = input() data=list(data) data.sort()

Now the variable "data" will have lexicographically sorte`d input provided.


In case you aren't dealing with a collection of simple strings but would still like to sort by natural sort order rather than lexicographic order:

Suppose you have a collection of object instances that you'd like to sort by a particular attribute and the attribute values can start in either upper or lower case then you can do something like this:

sorted(objects, lambda object: object.attr1.lower())

assuming attr1 is of type string. Why does this work? Because you are converting all the sorting keys into the same case for the purpose of sorting thus defeating lexicographical sorting. Without the use of lower() or upper() would result in lexicographic sort order rather than natural alphabetical sort order.


Use the natsort library. Better to use library than a stackoverflow code solution. (Read somewhere in SO only)

0

精彩评论

暂无评论...
验证码 换一张
取 消