日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python3moduleoftheweek中文_[翻译]Python Module of The Week: Counter

發布時間:2023/12/19 python 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python3moduleoftheweek中文_[翻译]Python Module of The Week: Counter 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Counter是一個來跟蹤加入多少個相同值的容器。

初始化:

Counter支持三種形式的初始化。它的構造器可以被一組元素來調用,一個包含鍵值和計數的字典,或者使用關鍵字參數字符串名稱到計數的映射。

import collections

print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])

print collections.Counter({'a':2, 'b':3, 'c':1})

print collections.Counter(a=2, b=3, c=1)

這三種形式的初始化的結果都是相同的。

$ python collections_counter_init.py

Counter({'b': 3, 'a': 2, 'c': 1})

Counter({'b': 3, 'a': 2, 'c': 1})

Counter({'b': 3, 'a': 2, 'c': 1})

一個空的Counter可以通過無參構造,并且使用update()方法賦值:

import collections

c = collections.Counter()

print 'Initial :', c

c.update('abcdaab')

print 'Sequence:', c

c.update({'a':1, 'd':5})

print 'Dict :', c

計數的值跟隨新的數據而增加,而不是被取代。在這個例子里,a的計數從3變為4。

$ python collections_counter_update.py

Initial : Counter()

Sequence: Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})

Dict : Counter({'d': 6, 'a': 4, 'b': 2, 'c': 1})

訪問Counts

一旦一個Counter被賦值了,它的值可以使用字典API去獲得

import collections

c = collections.Counter('abcdaab')

for letter in 'abcde':

print '%s : %d' % (letter, c[letter])

Counter不會對不知道的的數據項報KeyError. 如果一個值沒有在輸入中出現,它的計數為0

$ python collections_counter_get_values.py

a : 3

b : 2

c : 1

d : 1

e : 0

elements()方法返回一個產生所有對于Counter是已知數據項的迭代器

import collections

c = collections.Counter('extremely')

c['z'] = 0

print c

print list(c.elements())

元素的順序是沒有保證的,而且所有元素的計數如果小于0是沒有包含在內的。

$ python collections_counter_elements.py

Counter({'e': 3, 'm': 1, 'l': 1, 'r': 1, 't': 1, 'y': 1, 'x': 1, 'z': 0})

['e', 'e', 'e', 'm', 'l', 'r', 't', 'y', 'x']

使用most_common()方法來產生一個第n長出現的輸入值的序列以及對應的計數。

import collections

c = collections.Counter()

with open('/usr/share/dict/words', 'rt') as f:

for line in f:

c.update(line.rstrip().lower())

print 'Most common:'

for letter, count in c.most_common(3):

print '%s: %7d' % (letter, count)

這個例子計數系統字典里所有出現的字符,然后產生一個頻率分布,然后打印出最長出現的三個字符。給most_common()不賦參數,會產生一個所有數據項的序列,依據頻率排序。

$ python collections_counter_most_common.py

Most common:

e: 235331

i: 201032

a: 199554

作者:bluescorpio

總結

以上是生活随笔為你收集整理的python3moduleoftheweek中文_[翻译]Python Module of The Week: Counter的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。