我已成功按字数排序。
def countem(s, n):
hasht = {word: 0 for word in s.split()}
for word in s.split():
hasht[word] += 1
srted = sorted(list(hasht.keys()),
key=lambda word: hasht[word], reverse=True)
return srted
print(countem("Hackers love bits, so does Alex Alex has just started his
career as hacker and found a special binary", 2))
答案 0 :(得分:2)
首先,将hasht
替换为collections.Counter
然后您只需将2个critera输入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'
),但这可以更改。