青青草免费线看线看|啊在车上停不下来了|国产少女免费观看电视剧|仑乱88MAV|精品老司机在线观看视频|国产一区二区三区高清免费视频|在线观看免费777av

python怎么用Counter計數器?( 二 )


```
Counter會自動統計多個列表中每個元素的出現次數,并以字典的形式返回計數結果 。在上面的例子中,'orange'出現了7次,'apple'出現了4次,'banana'出現了3次 。
六、使用Counter計數器的常用方法
除了直接使用Counter統計元素出現次數之外,Counter還提供了一些常用方法,例如:
1. most_common(n)方法:返回出現次數最多的n個元素及其計數值,n默認為None,表示返回所有元素及其計數值 。
例如,下面的代碼演示了如何使用most_common(n)方法返回出現次數最多的3個元素及其計數值:
```python
from collections import Counter
lst = ['apple', 'banana', 'orange', 'apple', 'orange', 'orange']
cnt = Counter(lst)
print(cnt.most_common(3))
```
輸出結果為:
```python
[('orange', 3), ('apple', 2), ('banana', 1)]
```
2. update(iterable)方法:將iterable中的元素計入Counter中 。
例如,下面的代碼演示了如何使用update(iterable)方法將一個元素列表計入Counter中:
```python
from collections import Counter
lst = ['apple', 'banana', 'orange', 'apple', 'orange', 'orange']
cnt = Counter()
cnt.update(lst)
print(cnt)
```
輸出結果為:
```python
Counter({'orange': 3, 'apple': 2, 'banana': 1})
```
3. elements()方法:返回Counter中的所有元素,相當于把每個元素重復計數次數后再返回 。
例如,下面的代碼演示了如何使用elements()方法返回Counter中的所有元素:
```python
from collections import Counter
lst = ['apple', 'banana', 'orange', 'apple', 'orange', 'orange']
cnt = Counter(lst)
print(list(cnt.elements()))
```
輸出結果為:
```python
['apple', 'apple', 'orange', 'orange', 'orange', 'banana']
```
4. subtract(iterable)方法:將iterable中的元素從Counter中減去 。
例如,下面的代碼演示了如何使用subtract(iterable)方法將一個元素列表從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)
cnt.subtract(lst1)
print(cnt)
```
輸出結果為:
```python
Counter({'orange': 4, 'banana': 2, 'apple': 2})
```
【python怎么用Counter計數器?】七、

猜你喜歡