Python_collections模塊


collections 模塊----Python標准庫,是數據結構常用模塊

常用類型有:

  計數器(Counter)

  雙向隊列(deque)

  默認字典(defaultdict)

  有序字典(OrderedDict)

  可命名元組(namedtuple)

 

一、Counter

主要功能:將元素數量統計,然后計數返回一個字典,鍵為元素,值為元素個數

from collections import  Counter

str="abcbcaccbbad"
li=[2,3,43,3,45,54,33,33,1]
d={'d':3,'f':4,'g':3,'h':5}

#獲取元素個數,返回字典
print(dict(Counter(str)))
print(dict(Counter(d)))
print(dict(Counter(li)))

#most_common(int) 按照元素出現的次數進行從高到低的排序,返回前int個元素的字典
print(Counter(str).most_common(2))

#elements返回經過計算器Counter后的元素,返回的是一個迭代器
print(''.join(Counter(str).elements()))

#update更新,做加法,加上對應的個數
x=Counter(str)
x.update("sas1")
print(dict(x))

#subtract,做減法,減去對於的個數
y=Counter(li)
y.subtract([3,2])
print(dict(y))
print(y)

#獲取key和value
print(list(Counter(str).items())) #字典的key和value
print(list(Counter(str).keys())) #字典的key
print(list(Counter(str).values())) #字典的value

 


免責聲明!

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



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