首页 > 解决方案 > 如何返回字符串中最常见的字母并根据它们的频率计数对它们进行排序

问题描述

我有这个字符串:s = "china construction bank"。我想创建一个函数,返回 3 个最常见的字符,并按出现频率和出现次数对它们进行排序,但如果 2 个字符出现相同的次数,则应根据字母顺序对它们进行排序。我还想在单独的行中打印每个字符。

我现在已经构建了这段代码:

from collections import Counter
def ordered_letters(s, n=3):
    ctr = Counter(c for c in s if c.isalpha())
    print ''.join(sorted(x[0] for x in ctr.most_common(n)))[0], '\n', ''.join(sorted(x[0] for x in ctr.most_common(n)))[1], '\n', ''.join(sorted(x[0] for x in ctr.most_common(n)))[2]`

应用于上述字符串的这段代码将产生:

a 
c 
n

但这不是我真正想要的,我想要的输出是:

1st most frequent: 'n'. Appearances: 4
2nd most frequent: 'c'. Appearances: 3
3rd most frequent: 'a'. Appearances: 2

我被困在必须按字母顺序打印具有相同频率的字符的部分。我怎么能这样做?

非常感谢您提前

标签: pythonstringpython-2.7sortingcounter

解决方案


您可以使用heapq.nlargest自定义排序键。我们-ord(k)用作辅助排序器以按升序排序。使用堆队列比sorted不需要对Counter对象中的所有项目进行排序要好。

from collections import Counter
from heapq import nlargest

def ordered_letters(s, n=3):
    ctr = Counter(c.lower() for c in s if c.isalpha())

    def sort_key(x):
        return (x[1], -ord(x[0]))

    for idx, (letter, count) in enumerate(nlargest(n, ctr.items(), key=sort_key), 1):
        print('#', idx, 'Most frequent:', letter, '.', 'Appearances:', count)

ordered_letters("china construction bank")

# 1 Most frequent: n . Appearances: 4
# 2 Most frequent: c . Appearances: 3
# 3 Most frequent: a . Appearances: 2

推荐阅读