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

  • A+
Category:Languages

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?

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: