如何按出现次数排序,以及是否出现同样的字母排序?

时间:2018-06-11 12:09:10

标签: python python-3.x sorting

我已成功按字数排序。

    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))

1 个答案:

答案 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'),但这可以更改。