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:
(Capitals following at least one lowercased character doesn't matter.)
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
You can use :
print(sorted(names,key = lambda x: (not x.isupper(), x)))
>>> ['JOE', 'WILFRIED', 'Kate', 'alfred', 'denis']
UPDATED :
...
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