Sort list of strings in natural fashion

  • A+
Category:Languages

I have the following:

sorted( ("A","a","b","B","CC","c"), key=lambda x: x.lower() ) 

Which gives:

['A', 'a', 'b', 'B', 'c', 'CC'] 

How do I sort it like this:

['a', 'A', 'b', 'B', 'c', 'CC'] 

where if there are two values the same, the lower form comes first - a before A.

I'm guessing I do something like this:

sorted( ("A","a","b","B","CC","c"), key=lambda x: (x.lower(),x) ) 

but this gives A before a:

['A', 'a', 'B', 'b', 'c', 'CC'] 

How do I do the opposite?

UPDATE

To clarify things further, the following strings: ["A","a","aA","aa"] should be sorted as:

["a","A","aa","aA"] 

So "aa" before "aA" and "aaA" before "aAa" etc.

So:

lst = ["A","aA","aa","aaa","aAa","aaA","b","B","CC","c"] 

should sort to:

['A', 'aa', 'aA', 'aaa', 'aaA', 'aAa', 'b', 'B', 'c', 'CC'] 

 


You could do:

lst = ["A","a","b","B","CC","c"]  result = sorted(lst, key= lambda x: (x.lower(), not x.islower())) print(result) 

Output

['a', 'A', 'b', 'B', 'c', 'CC'] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: