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']
By default, the sort() method sorts the list in ASCIIbetical order rather than actual alphabetical order. This means uppercase letters come before lowercase letters. This causes the sort() function to treat all the list items as if they were lowercase without actually changing the values in the list.
Method #1 : Using sort() + isupper() In this, we perform task of checking for uppercase using isupper(), and sort() to perform task of sorting.
Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.
As aforementioned, the sort() method can be used to sort a list alphabetically in Python. However, this method permanently changes the order of the items in the list.
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')
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With