如何使用Python识别序列中最频繁出现的项目?

问题

您需要确定序列中最频繁出现的项目。

我们可以使用计数器跟踪序列中的项目。

什么是柜台?

“ Counter”是一个映射,其中包含每个键的整数计数。更新现有键会增加其数量。该对象用于计算可哈希对象的实例或作为多集。

执行数据分析时,“ Counter”是您最好的朋友之一。

这个对象在Python中已经存在很长时间了,因此对于很多人来说,这将是一个快速回顾。我们将从从集合中导入Counter开始。

from collections import Counter

传统字典,如果缺少键,将引发键错误。如果找不到该键,Python的词典将以键错误回答。

# An empty dictionary
dict = {}

# check for a key in an empty dict
dict['mystring']

# Error message
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-12-1e03564507c6> in <module>
      3  
      4 # check for a key in an empty dict
----> 5 dict['mystring']
      6
      7 # Error message
KeyError: 'mystring'

在这种情况下,如何避免出现关键错误异常?

计数器是字典的子类,具有非常类似于字典的行为,但是,如果您查找丢失的键而不是引发键错误,则它只会返回零。

# define the counter
c = Counter()


# check for the unavailable key
print(f"Ouput\n{c['mystring']}")

输出结果

0

c['mystring'] += 1
print(f"Ouput\n{c}")

输出结果

计数器({'mystring':1})

print(f"Ouput\n{type(c)}")

输出结果

<class'collections.Counter'>

序列中最频繁出现的项目

计数器的另一个好处是,您可以列出对象列表,它将为您计数。它使我们不必为了构建计数器而构建循环。

Counter
('Peas porridge hot peas porridge cold peas porridge in the pot nine days old'.split())

Counter({'Peas':1,'portrait':3,'hot':1,'peas':2,'cold':1,'in':1,'the':1,'pot':1 ,'nine':1,1,'days':1,'old':1})

拆分将执行的操作是将字符串分割成单词列表。它在空白处分割。

“ Counter”将遍历该列表并计数所有单词,从而为我们提供输出中显示的计数。

还有更多,我也可以数出该短语中最常用的词。

most_common()方法将为我们提供频繁出现的项目。

count = Counter('Peas porridge hot peas porridge cold peas porridge in the pot nine days old'.split())
print(f"Ouput\n{count.most_common(1)}")

输出结果

[('粥',3)]

print(f"Ouput\n{count.most_common(2)}")

乌普特

[('粥',3),('豌豆',2)]

print(f"Ouput\n{count.most_common(3)}")

输出结果

[('粥',3),('豌豆',2),('豌豆',1)]

注意,它返回了一个元组列表。元组的第一部分是单词,第二部分是单词计数。

Counter实例鲜为人知的功能是可以使用各种数学运算轻松地将它们组合在一起。

string = 'Peas porridge hot peas porridge cold peas porridge in the pot nine days old' another_string =
'Peas peas hot peas peas peas cold peas'

a = Counter(string.split())
b = Counter(another_string.split())


# Add counts
add = a + b
print(f"Ouput\n{add}")

输出结果

Counter({'peas':7,'porches':3,'Peas':2,'hot':2,'cold':2,'in':1,'the':1,'pot':1 ,'nine':1,'days':1,'old':1})

# Subtract counts
sub = a - b
print(f"Ouput\n{sub}")

输出结果

计数器({'porridge':3,'in':1,'the':1,'pot':1,'nine':1,'days':1,'old':1})

最后,Counter非常聪明地将数据存储在容器中。

如您在上方看到的,它在存储时将单词分组在一起,使我们能够将它们组合在一起,这通常被称为多集。

我们可以使用元素一次拉出一个单词。它不记得顺序,而是将所有单词放在一个短语中。

print(f"Ouput\n{list(a.elements())}")

输出结果

[“豌豆”,“粥”,“粥”,“粥”,“热”,“豌豆”,“豌豆”,“冷”,“中”,“该”,“锅”,“九”,“天”,“旧”]

print(f"Ouput\n{list(a.values())}")

输出结果

[1,3,1,2,1,1,1,1,1,1,1,1]

print(f"Ouput\n{list(a.items())}")

输出结果

[('Peas',1),('porridge',3),('hot',1),('peas',2),('cold',1),('in',1),( 'the',1),('pot',1),('nine',1),('days',1),('old',1)]]

猜你喜欢