python怎么用Counter计数器?

在Python中,Counter是一种用于计数的工具,可以方便地对元素进行计数,支持快速和简单的计数操作 。本篇文章将从多个角度分析如何使用Python中的Counter计数器 。
一、Counter概述

python怎么用Counter计数器?


Counter是Python中collections模块中的一个类,可以直接使用import collections语句导入 。
Counter可以接受任何可迭代对象作为输入,包括列表、元组、字符串、字典等 。Counter会统计每个元素出现的次数,并以字典的形式返回计数结果 。
例如,下面的代码演示了如何使用Counter计数器:
```python
from collections import Counter
lst = ['apple', 'banana', 'orange', 'apple', 'orange', 'orange']
cnt = Counter(lst)
print(cnt)
```
输出结果为:
```python
Counter({'orange': 3, 'apple': 2, 'banana': 1})
```
Counter会自动统计每个元素的出现次数,并以字典的形式返回计数结果 。在上面的例子中,'orange'出现了3次,'apple'出现了2次,'banana'出现了1次 。
二、使用Counter计数器统计字符串中字符出现次数
Counter计数器可以方便地统计字符串中字符出现的次数 。例如,下面的代码演示了如何使用Counter计数器统计字符串中字符出现的次数:
```python
from collections import Counter
s = 'hello, world!'
cnt = Counter(s)
print(cnt)
```
输出结果为:
```python
Counter({'l': 3, 'o': 2, 'e': 1, 'h': 1, ',': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1})
```
Counter会自动统计每个字符的出现次数,并以字典的形式返回计数结果 。在上面的例子中,'l'出现了3次,'o'出现了2次,'e'、'h'、','、' '、'w'、'r'、'd'、'!'各出现了1次 。
三、使用Counter计数器统计列表中元素出现次数
Counter计数器可以方便地统计列表中元素出现的次数 。例如,下面的代码演示了如何使用Counter计数器统计列表中元素出现的次数:
```python
from collections import Counter
lst = ['apple', 'banana', 'orange', 'apple', 'orange', 'orange']
cnt = Counter(lst)
print(cnt)
```
输出结果为:
```python
Counter({'orange': 3, 'apple': 2, 'banana': 1})
```
Counter会自动统计每个元素的出现次数,并以字典的形式返回计数结果 。在上面的例子中,'orange'出现了3次,'apple'出现了2次,'banana'出现了1次 。
四、使用Counter计数器统计字典中元素出现次数
Counter计数器也可以方便地统计字典中元素出现的次数 。例如,下面的代码演示了如何使用Counter计数器统计字典中元素出现的次数:
```python
from collections import Counter
dct = {'apple': 3, 'banana': 2, 'orange': 1}
cnt = Counter(dct)
print(cnt)
```
输出结果为:
```python
Counter({'apple': 1, 'banana': 1, 'orange': 1})
```
Counter会自动统计字典中每个元素的出现次数,并以字典的形式返回计数结果 。在上面的例子中,'apple'、'banana'、'orange'各出现了1次 。
五、使用Counter计数器统计多个列表中元素出现次数
Counter计数器还可以方便地统计多个列表中元素出现的次数 。例如,下面的代码演示了如何使用Counter计数器统计多个列表中元素出现的次数:
```python
from collections import Counter
lst1 = ['apple', 'banana', 'orange', 'apple', 'orange', 'orange']
lst2 = ['apple', 'orange', 'banana', 'banana']
lst3 = ['orange', 'apple', 'orange', 'orange']
cnt = Counter(lst1 + lst2 + lst3)
print(cnt)
```
输出结果为:
```python
Counter({'orange': 7, 'apple': 4, 'banana': 3})

猜你喜欢