taalf taalf - 1 month ago 16
Python Question

Python : sorting a list of strings, all capitalized first

How to sort a list of strings so that the number of capitals beginning the string is the main criterion?

What I have:

names = ["JOE", "Kate", "WILfried", "alfred", "denis"]

print sorted(names)

>>> ['JOE', 'Kate', 'WILfried', 'alfred', 'denis']


What I would like:

>>> ['JOE', 'WILfried', 'Kate', 'alfred', 'denis']


EDIT

In other words, I would like:


  • in first positions, sorted strings beginning with n capitals

  • then, sorted strings beginning with n-1 capitals

  • " " " " " " " " " " " " " " " " " " " " " " " " " n-2 " " " " " "

  • etc.



(Capitals appearing after a lowercased character can be treated as lowercased characters: "candy" = "cANDY" = "cAnDy")

Answer Source

Here is a (somewhat ugly) solution:

names = ['JOE', 'Kate', 'WILfried', 'alfred', 'denis']
k = lambda s: ([-i for i, u in enumerate(map(str.isupper, s)) if not u],
               s.lower())
print sorted(names, key=k)
>>> ['JOE', 'WILfried', 'Kate', 'denis', 'alfred']

Maybe you want to put that lambda as a proper function.