python3 Counter模塊


from collections import Counter

c = Counter("周周周周都方法及")
print(c)
print(type(c))
print('__iter__' in dir(c))
print('__next__' in dir(c))
print('items' in dir(c))

執行結果:

Counter({'': 4, '': 1, '': 1, '': 1, '': 1})
<class 'collections.Counter'>
True
False
True

 

'''get()方法獲取元素出現的次數,沒找到,則為None'''
print(c.get(""))
print(c.get(""))

'''和字典get()方法一樣'''
dic = {"a": 1, "b": 2, "c": 3}
print(dic.get('a'))
print(dic.get('g'))

執行結果:

4
None
1
None

 

for k, v in c.items():
    print("'"+k+"'的數量:"+str(v))

'''統計列表列表中"周傑倫'出現的次數'''
lst = ["趙本山", "河正宇", "黃海", "追擊者", "周傑倫", "周傑倫"]
c = Counter(lst)
print(c.get("周傑倫"))

執行結果:

''的數量:4
''的數量:1
''的數量:1
''的數量:1
''的數量:1
2

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM