Сначала замените hasht
на collections.Counter
, а затем вы можете просто передать 2 критерия в sorted
:
from collections import Counter
from pprint import pprint
def countem(s):
return sorted(Counter(s.split()).items(),
key= lambda x: (-x[1], x[0]))
pprint(countem("Hackers love bits, so does Alex Alex has just started his career as hacker and found a special binary"))
Вывод:
[('Alex', 2),
('Hackers', 1),
('a', 1),
('and', 1),
('as', 1),
('binary', 1),
('bits,', 1),
('career', 1),
('does', 1),
('found', 1),
('hacker', 1),
('has', 1),
('his', 1),
('just', 1),
('love', 1),
('so', 1),
('special', 1),
('started', 1)]
Примечание. Я реализовал этос учетом регистра (следовательно, 'Hackers'
появляется перед 'a'
), но это можно изменить.