python 学习_collection,,collection


collections模块在内置数据类型(dict  list  set  tuple)的基础上, 还提供了几个额外的数据类型

  ChainMap Counter depue defaultdict namedtuple OrderedDict

1. namedtuple 生成可以使用名字来访问元素内容的tuple子集

2. deque 双端队列 可以快速的从另一端追加和退出对象

3. Counter 计算器 主要用来计数

4. OrderedDict 有序字典

5. defaultdict 带有默认值的字典



#  1.  namedtuple      生成可以使用名字来访问元素内容的tuple子集from collections import namedtuplePoint = namedtuple("Point",[‘x‘,‘y‘])p = Point(1,2)print(p.x)      #1print(p.y)      #2print(p)        #Point(x=1, y=2)

# 2.  deque 双端队列   可以快速的从另一端追加和退出对象from collections import  dequeq = deque([‘a‘,‘b‘,‘c‘])q.append(‘x‘)q.appendleft(‘y‘)print(q)

#3.  Counter 计算器   主要用来计数from  collections import  Counterc =  Counter()for word in [‘red‘, ‘blue‘, ‘red‘, ‘green‘, ‘blue‘, ‘blue‘]:    c[word] = c[word] + 1print(c)        # Counter({‘blue‘: 3, ‘red‘: 2, ‘green‘: 1})

# 4.  OrderedDict      有序字典# 使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。# 如果要保持Key的顺序,可以用OrderedDict:from collections import  OrderedDictd = dict(a=1,b=2,c=3)od = OrderedDict(a=1,b=2,c=3)print(od)  # # OrderedDict的   Key    是有序的
from collections import  OrderedDictod = OrderedDict(a=1,b=2,c=3)od[‘z‘] =222print(od.keys())  # odict_keys([‘a‘, ‘b‘, ‘c‘, ‘z‘])
# OrderedDict 可以实现FIFO(先进先出)的dict 当容量超出限制时, 先删除最早添加的key



# 5.  defaultdict      带有默认值的字典# 使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict:from collections import  defaultdictdd = defaultdict(lambda: ‘WWWW‘)dd[‘key1‘] = ‘abc‘print(dd[‘key1‘])   # abcprint(dd[‘key12‘])      # WWWW   不存在 返回默认值s = ‘mississippi‘d = collections.defaultdict(int)for i in s:    d[i] +=1print(d)        #defaultdict(<class ‘int‘>, {‘m‘: 1, ‘i‘: 4, ‘s‘: 4, ‘p‘: 2})










python 学习_collection

评论关闭