Python中使用Counter进行字典创建以及key数量统计的方法

  • Post category:Python

当我们需要统计一个列表中各元素出现的次数时,可以使用Python中的Counter类来进行统计。同时,Counter类也可以用于快速创建一个字典,将列表元素作为键,元素出现的次数作为对应的值。下面是Python中使用Counter进行字典创建以及key数量统计的方法的完整攻略。

创建Counter对象

我们可以通过对列表、元组、字符串等进行传入Counter类的方式来创建一个Counter对象。

from collections import Counter

# 字符串
s = 'hello world'
counter_s = Counter(s)
print(counter_s)

# 列表
lst = [1, 2, 3, 4, 1, 2, 3, 1, 2]
counter_lst = Counter(lst)
print(counter_lst)

# 元组
tup = (1, 2, 3, 4, 1, 2, 3, 1, 2)
counter_tup = Counter(tup)
print(counter_tup)

输出结果如下所示:

Counter({'l': 3, 'o': 2, ' ': 1, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 1})
Counter({1: 3, 2: 3, 3: 2, 4: 1})
Counter({1: 3, 2: 3, 3: 2, 4: 1})

Counter对象的操作

Counter类提供了许多操作,可以方便我们进行信息统计和处理。

获取出现最多的n个元素

我们可以使用most_common()函数来获取出现次数最多的n个元素及其出现次数。

from collections import Counter

# 列表
lst = ['apple', 'banana', 'orange', 'apple', 'orange', 'pear', 'banana', 'banana', 'grape']
counter_lst = Counter(lst)
print(counter_lst.most_common(2))

输出结果如下所示:

[('banana', 3), ('orange', 2)]

字典的创建

我们可以使用Counter类快速创建一个字典,将列表元素作为键,元素出现的次数作为对应的值。

from collections import Counter

# 列表
lst = ['apple', 'banana', 'orange', 'apple', 'orange', 'pear', 'banana', 'banana', 'grape']
counter_lst = Counter(lst)
res_dict = dict(counter_lst)
print(res_dict)

输出结果如下所示:

{'apple': 2, 'banana': 3, 'orange': 2, 'pear': 1, 'grape': 1}

总结

以上就是Python中使用Counter进行字典创建以及key数量统计的方法的完整攻略。通过Counter类的操作,我们可以非常方便地完成对列表中元素出现次数的统计和字典的创建。