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