Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : sorting a list of strings, all capitalized first [closed]

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 following at least one lowercased character doesn't matter.)

like image 670
taalf Avatar asked Jan 04 '23 14:01

taalf


2 Answers

Following function satisfies the requirement

l = ['JOE', 'Kate', 'WILfried', 'alfred', 'denis']
def k(x):
  for i,j in enumerate(x):
    if j.islower():
      return (-i,x)
  return (-len(x),x)

print(sorted(l,key=k))

This gives following output:

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

The function k gives weight to the number of uppercases appearing at the start of the string.
EDIT: Thanks @jdeseha for edits

like image 96
Rajan Chauhan Avatar answered Jan 14 '23 02:01

Rajan Chauhan


You can use :

print(sorted(names,key = lambda x: (not x.isupper(), x)))
>>> ['JOE', 'WILFRIED', 'Kate', 'alfred', 'denis']

UPDATED :

...

like image 27
PRMoureu Avatar answered Jan 14 '23 04:01

PRMoureu