Sort list of strings in natural fashion

  • A+

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?


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


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


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) 


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


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