欧美国产高清污视频在线观看-欧美久久综合九色综合-国产黄色自拍网站在线-国产三级精品三级在专区精-97中文字幕一区二区-大吊操白虎学生妹逼-精品久久久久亚洲综合网-青青草原国产av一区欧美-国产在线一区二区三区在线

python怎么用Counter計數器?

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

python怎么用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})

猜你喜歡