Python : sorting a list of strings, all capitalized first -
how sort list of strings number of capitals beginning string main criterion?
what have:
names = ["joe", "kate", "wilfried", "alfred", "denis"] print sorted(names) >>> ['joe', 'kate', 'wilfried', 'alfred', 'denis'] what like:
>>> ['joe', 'wilfried', 'kate', 'alfred', 'denis'] edit
in other words, like:
- in first positions, sorted strings beginning n capitals
- then, sorted strings beginning n-1 capitals
- " " " " " " " " " " " " " " " " " " " " " " " " " n-2 " " " " " "
- etc.
(capitals following @ least 1 lowercased character doesn't matter.)
following function satisfies requirement
l = ['joe', 'kate', 'wilfried', 'alfred', 'denis'] def k(x): 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 number of uppercases appearing @ start of string.
edit: @jdeseha edits
Comments
Post a Comment