python--collections容器
简介
collections包含了一些特殊的容器,针对Python内置的容器,例如list、dict、set和tuple,提供了另一种选择;
namedtuple,可以创建包含名称的tuple;
deque,类似于list的容器,可以快速的在队列头部和尾部添加、删除元素;
Counter,dict的子类,计算可hash的对象;
OrderedDict,dict的子类,可以记住元素的添加顺序;
defaultdict,dict的子类,可以调用提供默认值的函数;
Counter:
from collections import * cnt = Counter() #创建对象--字典的之类 wordList = ["a","b","c","c","a","a"] for word in wordList: cnt[word] += 1 #【说明:针对相应key的值进行计算】 print(cnt) #Counter({‘a‘: 3, ‘c‘: 2, ‘b‘: 1})
from collections import * c = Counter()#一个新的,空的counter print(c) #Counter() c = Counter("gallahad")#从可迭代的字符串初始化counter print(c) #Counter({‘a‘: 3, ‘l‘: 2, ‘g‘: 1, ‘h‘: 1, ‘d‘: 1}) c = Counter({‘red‘:4,‘blue‘:2}) #从映射初始化counter print(c) #Counter({‘red‘: 4, ‘blue‘: 2}) c = Counter(cats = 4,dogs = 8) #从args初始化counter print(c) #Counter({‘dogs‘: 8, ‘cats‘: 4})
from collections import *#Counter对象类似于字典,如果某个项缺失,会返回0,而不是报出KeyError;c = Counter([‘eggs‘,‘ham‘])print(c[‘bacon‘]) #没有‘bacon‘,返回0del c[‘eggs‘] #删除eggs元素print(c) #Counter({‘ham‘: 1})
Counter对象支持以下三个字典不支持的方法,elements(),most_common(),subtract();
from collections import * c = Counter(a=2,b=4,c=0,d=-2,e = 1) print(c) #Counter({‘b‘: 4, ‘a‘: 2, ‘e‘: 1, ‘c‘: 0, ‘d‘: -2}) print(c.elements()) #c.elements()是一个迭代器--返回迭代器的地址 L=list(c.elements()) #element(),返回一个迭代器,每个元素重复的次数为它的数目,顺序是任意的顺序,如果一个元素的数目少于1,那么elements()就会忽略它; print(L) #[‘a‘, ‘a‘, ‘b‘, ‘b‘, ‘b‘, ‘b‘, ‘e‘]
from collections import * c = Counter(‘abracadabra‘) print(c) #Counter({‘a‘: 5, ‘b‘: 2, ‘r‘: 2, ‘c‘: 1, ‘d‘: 1}) a=c.most_common(3) #most_common(),返回一个列表,包含counter中n个最大数目的元素,如果忽略n或者为None,most_common()将会返回counter中的所有元素,元素有着相同数目的将会以任意顺序排列; print(a) #[(‘a‘, 5), (‘b‘, 2), (‘r‘, 2)] b=c.most_common() print(b) d=c.most_common(None) print(d)
from collections import * c = Counter(a=4,b=2,c=0,d=-2,e=9) d = Counter(a=1,b=2,c=-3,d=4,f=77) print(c,d) c.subtract(d) #c中相应的值减去d中相应的值,结果保存到c中 print(c) c = Counter(a=4,b=2,c=0,d=-2,e=9) c.update(d) #c中相应的值加上d中相应的值,结果保存到c中 print(c)
相关推荐
yangkang 2020-11-09
alien 2020-11-15
ChlatZed 2020-11-11
远远的山 2020-11-09
xysoul 2020-11-03
onepiecedn 2020-10-29
lnkToKing 2020-10-29
ChlatZed 2020-10-27
谢恩铭 2020-10-23
yuanye0 2020-10-15
liverlife 2020-10-10
somyjun 2020-09-29
xiaoying 2020-09-28
kunyus 2020-09-25
dusuanyun 2020-09-21
newisI 2020-09-01
afanti 2020-09-14