List r
:
r= [['Paris', 10], ['amsterdam', 5], ['London', 18], ['london', 15], ['Berlin', 2], ['Stockholm', 4], ['oslo', 14], ['helsinki', 16], ['Zurich', 17]]
If I do a reverse sort:
sorted(r, reverse=True)
[['oslo', 14], ['london', 15], ['helsinki', 16], ['amsterdam', 5], ['Zurich', 17], ['Stockholm', 4], ['Paris', 10], ['London', 18], ['Berlin', 2]]
What I want is to start with Upper case elements and than the lower case elements.
[ ['Zurich', 17], ['Stockholm', 4], ['Paris', 10], ['London', 18], ['Berlin', 2], ['oslo', 14], ['london', 15], ['helsinki', 16], ['amsterdam', 5]]
Is there an easy way in Python3 to sort the list as I want?
There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.
In order to reverse the original order of a list, you can use the reverse() method. The reverse() method is used to reverse the sequence of the list and not to arrange it in a sorted order like the sort() method. reverse() method reverses the sequence of the list permanently.
Python sorted() FunctionThe 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.
Everything is possible with a custom key
function:
>> sorted(r, key=lambda e: (not e[0].islower(), e[0]), reverse=True)
[['Zurich', 17], ['Stockholm', 4], ['Paris', 10], ['London', 18], ['Berlin', 2],
['oslo', 14], ['london', 15], ['helsinki', 16], ['amsterdam', 5]]
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