Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']
like image 271
user2388809 Avatar asked May 16 '13 07:05

user2388809


People also ask

How do you sort lowercase and uppercase in Python?

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.

How do you sort uppercase in Python?

Method #1 : Using sort() + isupper() In this, we perform task of checking for uppercase using isupper(), and sort() to perform task of sorting.

How do you arrange a list in alphabetical order in Python?

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.

Does sort () sort alphabetically?

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.


2 Answers

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')

like image 72
Jon Clements Avatar answered Nov 08 '22 08:11

Jon Clements


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']
like image 31
oleg Avatar answered Nov 08 '22 09:11

oleg