user2388809
user2388809

Reputation: 115

python: how to sort lists alphabetically with respect to capitalized letters

I'm trying to sort a list alphabetically, where capital letters should come before lower case letters.

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

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

I've 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']

Upvotes: 7

Views: 7042

Answers (2)

oleg
oleg

Reputation: 4182

Interesting how such a list supposed to sort following list

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

Proposed solution produce following result

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

I can propose more complicated solution with different result

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

Upvotes: 5

Jon Clements
Jon Clements

Reputation: 142216

Create a tuple as your key instead:

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

This means the sort order for lower-case doesn't change ('a', 'a') but means the first key for upper case puts it level with the lower-case equivalent, then sorts before it: eg ('a', 'A') < ('a', 'a')

Upvotes: 15

Related Questions