collections中的Counter筆記

note from :

https://blog.csdn.net/Shiroh_ms08/article/details/52653385

重點代碼:

from collections import Counter
c=Counter('abbbbcdefg')

# output
c
Counter({'a': 1, 'b': 4, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1})
c['z']
0  # 針對c中不存在的元素,默認爲0
del c['a']  # 將a的計數設置成0
# 返回一個迭代器,其中的元素重複次數和它的count一樣多,元素返回次序任意,如果count小於1,將會被忽略
list(c.elements())
# output
['f', 'e', 'b', 'b', 'd', 'c', 'g']  
list(c.most_common(2))  # 次序任意,提取前兩個元素
[('a', 3), ('e', 1)]
c.subtract('b')  # 扣除某個具體元素後or 可迭代or可哈希對象,該元素計數爲0,有點兒類似於del
# output
Counter({'b': 0, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1})

c.subtract(b=2,c=3,x=5)
# output
Counter({'a': 1, 'b': 2, 'c': -2, 'd': 1, 'e': 1, 'f': 1, 'g': 1, 'x': -5})
c.items()
# output
dict_items([('f', 1), ('e', 1), ('b', 2), ('a', 1), ('d', 1), ('c', -2), ('x', -5), ('g', 1)])
c+=Counter()
# Output

Counter({'a': 1, 'b': 2, 'd': 1, 'e': 1, 'f': 1, 'g': 1})

my_list=[1,2,3,4]
my_list[:-4:-1]  # 第三個索引代表倒序,第二個索引代表結束位置,(不包括結束位置)
[4, 3, 2]
c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c&d  # 返回每種元素的最小值
Counter({'a': 1, 'b': 1})

c = Counter(a=3, b=1, e=1)
d = Counter(a=1, b=2, f=-2)
print(c-d)  # 運算數不存在某元素,該元素默認爲0
print(c&d)
print(c|d)
Counter({'f': 2, 'a': 2, 'e': 1})
Counter({'b': 1, 'a': 1})
Counter({'a': 3, 'b': 2, 'e': 1})

小測試

# 可能根據每個字符所對應的ASCII碼來比較大小
d=Counter(b='love',k='you',z='lily')
d.most_common()
[('k', 'you'), ('b', 'love'), ('z', 'lily')]

'abc'*3
'abcabcabc'

['abc']*3
['abc', 'abc', 'abc']

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章