如何获得 most_common 频率。?

How can get the most_common frequencies.?


def CountFrequency(my_list):
    
    freq = {}
    
    for char in my_list:
        if char in freq:
            freq[char] += 1
        else:
            freq[char] = 1
    print(freq)
            
CountFrequency(emoji_list)

上面的代码生成了具有相应频率的表情符号字典。我怎样才能得到 most_common 频率

解法:

一旦你有了字典freq你就可以做这样的事情:

output = sorted([(key, val) for key, val in freq.items()], key=lambda x: -x[1])

这将生成一个按频率排序的列表。然后你可以只得到最频繁的:

output = output[0][0]

完整测试代码:

freq = {'a' : 40, 'b': 20, 'd': 90}
output = sorted([(key, val) for key, val in freq.items()], key=lambda x: -x[1])
print(output)

输出:

[('d', 90), ('a', 40), ('b', 20)]

进一步说明:

这个:

[(key, val) for key, val in freq.items()]

创建一个元组列表,其中每个元组包含一个 key-value 对。然后是 sorted()key 是:

lambda x: -x[1]

这只是一个函数,它给出元组中的第二个值(我们排序的那个)。我们有一个 - 符号,因为我们想要 递减 顺序。

所有内容一起给出 key-value 对的排序列表。然后我们可以得到第一个元组:

output[0]

这为我们提供了具有最高价值的 key-value 对。因为我们想要哪个项目是最频繁的,所以我们可以得到元组中的第一个项目(因为它是键),如下所示:

output[0][0]

然后可以将其再次保存到 output 以备后用,如下所示:

output = output[0][0]