Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list in python to make lowercase precede uppercase?

Tags:

python

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]

like image 619
yantiz Avatar asked Nov 30 '22 17:11

yantiz


2 Answers

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']
like image 96
John La Rooy Avatar answered Dec 05 '22 13:12

John La Rooy


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']
like image 26
inspectorG4dget Avatar answered Dec 05 '22 12:12

inspectorG4dget