在Python中,Counter是一種用于計數的工具,可以方便地對元素進行計數,支持快速和簡單的計數操作 。本篇文章將從多個角度分析如何使用Python中的Counter計數器 。
一、Counter概述

Counter是Python中collections模塊中的一個類,可以直接使用import collections語句導入 。
Counter可以接受任何可迭代對象作為輸入,包括列表、元組、字符串、字典等 。Counter會統(tǒng)計每個元素出現的次數,并以字典的形式返回計數結果 。
例如,下面的代碼演示了如何使用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會自動統(tǒng)計每個元素的出現次數,并以字典的形式返回計數結果 。在上面的例子中,'orange'出現了3次,'apple'出現了2次,'banana'出現了1次 。
二、使用Counter計數器統(tǒng)計字符串中字符出現次數
Counter計數器可以方便地統(tǒng)計字符串中字符出現的次數 。例如,下面的代碼演示了如何使用Counter計數器統(tǒng)計字符串中字符出現的次數:
```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會自動統(tǒng)計每個字符的出現次數,并以字典的形式返回計數結果 。在上面的例子中,'l'出現了3次,'o'出現了2次,'e'、'h'、','、' '、'w'、'r'、'd'、'!'各出現了1次 。
三、使用Counter計數器統(tǒng)計列表中元素出現次數
Counter計數器可以方便地統(tǒng)計列表中元素出現的次數 。例如,下面的代碼演示了如何使用Counter計數器統(tǒng)計列表中元素出現的次數:
```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會自動統(tǒng)計每個元素的出現次數,并以字典的形式返回計數結果 。在上面的例子中,'orange'出現了3次,'apple'出現了2次,'banana'出現了1次 。
四、使用Counter計數器統(tǒng)計字典中元素出現次數
Counter計數器也可以方便地統(tǒng)計字典中元素出現的次數 。例如,下面的代碼演示了如何使用Counter計數器統(tǒng)計字典中元素出現的次數:
```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會自動統(tǒng)計字典中每個元素的出現次數,并以字典的形式返回計數結果 。在上面的例子中,'apple'、'banana'、'orange'各出現了1次 。
五、使用Counter計數器統(tǒng)計多個列表中元素出現次數
Counter計數器還可以方便地統(tǒng)計多個列表中元素出現的次數 。例如,下面的代碼演示了如何使用Counter計數器統(tǒng)計多個列表中元素出現的次數:
```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})
猜你喜歡
- Python實現二分法算法實例
- python3如何新建工程?
- 盆栽凌霄花冬天怎么管理
- 球形鎖怎么定位開孔
- 球形鎖鎖舌失靈怎么辦呢?
- 球形冷凝管的使用方法有哪些?
- 收款提示器怎么設置
- 嗶哩嗶哩怎么添加購買人信息
- 怎么讓錄音變好聽
- WPS文檔怎么快速制作清明節(jié)放假通知海報
