Python: how to sort lists alphabetically by capital letters

I am trying to sort the list in alphabetical order where uppercase letters should appear before lowercase letters.

l = ['a', 'b', 'B', 'A'] 

sorted(l) should result in ['A','a','B','b']

I tried these two forms, but to no avail;

 >>> sorted(l, key=lambda s: s.lower()) ['a', 'A', 'b', 'B'] >>> sorted(l, key=str.lower) ['a', 'A', 'b', 'B'] 
+6
source share
2 answers

Create a tuple instead of your key:

 >>> sorted(lst, key=lambda L: (L.lower(), L)) ['A', 'a', 'B', 'b'] 

This means that the sort order for lower case does not change ('a', 'a') , but means that the first key for upper case puts it at the level with the lower equivalent, then sorts in front of it: for example, ('a', 'a') < ('a', 'a')

+9
source

I wonder how such a list should sort the following list

 lst = ['abb', 'ABB', 'aBa', 'AbA'] 

The proposed solution gives the following result

 >>> sorted(lst, key=lambda L: (L.lower(), L)) ['AbA', 'aBa', 'ABB', 'abb'] 

I can offer a more complex solution with different results

 >>> sorted(lst, key=lambda a: sum(([a[:i].lower(), a[:i]] for i in range(1, len(a)+1)),[])) ['ABB', 'AbA', 'aBa', 'abb'] 
+3
source

Source: https://habr.com/ru/post/945129/


All Articles