Reputation: 97
Sorry this may be a naive question. But I am a newbie to python and this confuses me for a while.
I know how to treat all strings as lowercase by applying str.lower(), but I don't know how to intentionally put elements with lowercase letter as the first letter before uppercase ones.
For clarification:
Here is a example list: [Bear, bear, Apple, apple]
I want it to be: [apple, Apple, bear, Bear]
Upvotes: 7
Views: 5838
Reputation: 304385
You can chain two sorts like this, since Python's sort is stable
>>> sorted(sorted(['Bear', 'bear', 'Apple', 'apple'], reverse=True), key=str.lower)
['apple', 'Apple', 'bear', 'Bear']
Or you can use a single sort, like this:
Python2:
>>> sorted(['Bear', 'bear', 'Apple', 'apple'], key=lambda x: (x.lower(), x.swapcase()))
['apple', 'Apple', 'bear', 'Bear']
Python3:
>>> sorted(['Bear', 'bear', 'Apple', 'apple'], key=lambda x: (x.casefold(), x.swapcase()))
['apple', 'Apple', 'bear', 'Bear']
Upvotes: 17
Reputation: 49330
Python's built-in sorting functions are stable, meaning that items will only move around on subsequent sorts if the new sorting key requires it. This means that you can simply sort multiple times, with a different key.
>>> my_list = ['Bear', 'bear', 'Apple', 'apple']
>>> my_list = sorted(my_list, key=str.istitle)
>>> my_list
['bear', 'apple', 'Bear', 'Apple']
>>> my_list = sorted(my_list, key=str.lower)
>>> my_list
['apple', 'Apple', 'bear', 'Bear']
Upvotes: 2
Reputation: 114035
In [95]: L = ['Bear', 'bear', 'Apple', 'apple']
In [96]: sorted(L, key=lambda s:(s.lower(), s[0].isupper()))
Out[96]: ['apple', 'Apple', 'bear', 'Bear']
Upvotes: 4