Skip to main content
 首页 » 编程设计

python之返回前 n 个最常出现的字符及其在 python 中各自的计数

2025年05月04日12JeffreyZhao

如何返回前 n 个最常出现的字符及其各自的计数 # 例如 'aaaaaabbbbcccc', 2 应该返回 [('a', 6 ), ('b', 4)] 在 python 中

我试过了

def top_chars(input, n): 
    list1=list(input) 
    list3=[] 
    list2=[] 
    list4=[] 
    set1=set(list1) 
    list2=list(set1) 
    def count(item): 
        count=0 
        for x in input: 
            if x in input: 
                count+=item.count(x) 
        list3.append(count) 
        return count 
 
    list2.sort(key=count) 
 
    list3.sort() 
    list4=list(zip(list2,list3)) 
    list4.reverse() 
    list4.sort(key=lambda list4: ((list4[1]),(list4[0])), reverse=True) 
    return list4[0:n] 
    pass 

但它不适用于输入 ("aabc",2) 它应该给出的输出是

[('a', 2), ('b', 1)] 

但我得到的输出是

[('a', 2), ('c', 1)] 

请您参考如下方法:

使用collections.Counter();它有一个 most_common() 方法可以做到这一点:

>>> from collections import Counter 
>>> counts = Counter('aaaaaabbbbcccc') 
>>> counts.most_common(2) 
[('a', 6), ('c', 4)] 

请注意,对于上述输入和 aabc 中的 b 和 c 都具有相同的计数,并且两者都可以是有效的顶级竞争者.因为您和 Counter 都是按计数排序然后反向输入,所以 c 排在 b 之前。

如果您使用 负数 作为排序关键字而不是反向排序,您将再次在 c 之前对 b 进行排序:

list4.sort(key=lambda v: (-v[1], v[0)) 

并不是说 Counter.most_common() 在您要求的元素少于柜台中的 key 时实际使用排序;它使用 heapq-based algorithm而不是只获取前 N 个项目。