Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Reverse Sort a nested list starting with Uppercase entries?

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?

like image 832
Reman Avatar asked Dec 03 '18 11:12

Reman


People also ask

Can you sort a nested list?

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.

How do you sort a list in reverse order?

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.

How do you sort a list alphabetically in Python with sort function?

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.


1 Answers

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]]
like image 78
DeepSpace Avatar answered Oct 22 '22 01:10

DeepSpace