【问题标题】:how to sort letters per their frequency in a word?如何根据单词中的频率对字母进行排序?
【发布时间】:2019-06-02 09:23:58
【问题描述】:

我想按单词中出现频率的降序对字母进行排序。但是,如果两个字母频率相同,则应选择按字母顺序排列的前一个字母。

我使用 Counter 来查找所有字母的频率,它会返回一个字典。如何按频率降序对它们进行排序,然后按字母顺序选择频率最高的 n 个字母

string='ddddaacccbb'
n=3
from collections import Counter
counter=Counter(string)

假设如果单词是'ddddaacccbb'并且n是3,那么它应该打印['a','c','d'],这里n是字母的数量。输出基于每个字母的最高频率,如果两个字母的频率相似,则选择按字母顺序排列的前一个。

【问题讨论】:

  • 那么n 是干什么用的?
  • 这些词是“字母”,而不是“字母”。
  • 如果按最高频率排序,不应该是['d', 'c', 'a', 'b']['d', 'c', 'b', 'a]吗?

标签: python sorting dictionary


【解决方案1】:

使用计数器的most_common()方法。

from collection import Counter
string = 'ddddaacccbb'
n = 3
count = Counter(string)
print([letter for letter, _ in count.most_common(n)])

输出将是

['d', 'c', 'a']

如果您希望输出按字母顺序,您可以对结果进行排序。

print(sorted(letter for letter, _ in count.most_common(n)))

输出:

['a', 'c', 'd']

【讨论】:

    【解决方案2】:

    您只需要通过以下方式从列表中检索前 n 个元素 Counter.most_common 并提取字母,按最常见到最不常见的排序由most_common 方法隐式完成

    string='aacccbbdddd'
    n=3
    from collections import Counter
    counter=Counter(string)
    
    #Get the letters of n top values
    res = [letter[0] for letter in counter.most_common(n)]
    print(res)
    

    输出将是

    ['d', 'c', 'a']
    

    【讨论】:

    • 但这不是这个家伙想要的输出。
    • 你说得对,我更正了@goodvibration 请看一下
    【解决方案3】:

    您可以使用sorted 并检索计数器的一部分:

    keys = sorted(counter, key=lambda x: (counter.get(x), x))
    # sort by value, then key
    result = keys[-n:]
    

    【讨论】:

      【解决方案4】:

      可以使用 sorted 函数的 key= 参数:

      对于大多数...最不频繁,相同频率按字母顺序排列:

      letters = sorted(counter,key=lambda c:(-counter[c],c))[:3]
      
      # ['d', 'c', 'a']  
      

      对于最少...最频繁的顺序,使用这个:

      letters = sorted(counter,key=lambda c:(counter[c],c))[-3:]
      
      # ['a', 'c', 'd']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-07
        • 2021-12-20
        相关资源
        最近更新 更多