larken

勤奋的人生才有价值

导航

collections模块

  1 :func:`namedtuple`factory function for creating tuple subclasses with named fields
  2 :class:`deque`list-like container with fast appends and pops on either end
  3 :class:`ChainMap`dict-like class for creating a single view of multiple mappings
  4 :class:`Counter`dict subclass for counting hashable objects
  5 :class:`OrderedDict`dict subclass that remembers the order entries were added
  6 :class:`defaultdict`dict subclass that calls a factory function to supply missing values
  7 :class:`UserDict`wrapper around dictionary objects for easier dict subclassing
  8 :class:`UserList`wrapper around list objects for easier list subclassing
  9 :class:`UserString`wrapper around string objects for easier string subclassing
 10 
 11 # 在Python中,大致将群集分为三种类型:序列类型、集合类型与映射类型
 12 # deque类
 13 # 对于队列或双向队队列的需求,建议使用collections模块中提供的deque类
 14 from collections import deque
 15 deque=deque([1,2,3])
 16 deque.appendleft(0)
 17 deque.appendleft(-1)
 18 print(deque)        # deque([-1, 0, 1, 2, 3])
 19 print(deque.pop())
 20 print(deque.popleft())
 21 deque.rotate(1)
 22 print(deque)
 23 deque.rotate(1)
 24 print(deque)
 25 
 26 # nametuple()函数
 27 # 如果想要个简单类,以便创建的实例能拥有字段名,实际上不用自定义
 28 from math import sqrt
 29 from collections import namedtuple
 30 class Point(namedtuple('Point',['x','y'])) :
 31     def len_from(self,other):
 32         return sqrt(pow(self.x - other.x,2)+pow(self.y - other.y,2))
 33 p1=Point(5,10)
 34 p2=Point(8,15)
 35 print(p1.len_from(p2))
 36 
 37 # OrderDict类
 38 from collections import OrderedDict
 39 from operator import itemgetter
 40 orgin_dict={'A':85,'B':90,'C':70}
 41 print(OrderedDict(sorted(orgin_dict.items(),key=itemgetter(0))))        # 按键排序
 42 # OrderedDict([('A', 85), ('B', 90), ('C', 70)])
 43 print(OrderedDict(sorted(orgin_dict.items(),key=itemgetter(1))))        # 按值排序
 44 # OrderedDict([('C', 70), ('A', 85), ('B', 90)])
 45 
 46 # defaultdict类
 47 # defaultdict接受一个函数,它创建的实例在指定的键不存在时,就会使用指定的函数来产生,并直接设置为键的对应值
 48 from collections import defaultdict
 49 names=['Justin','Monica','Irene','Pika','caterpillar']
 50 group_by_len=defaultdict(list)
 51 for name in names:
 52     key=len(name)
 53     group_by_len[key].append(name)
 54 for length in group_by_len:
 55     print(length,group_by_len[length])
 56 # 也可以使用defaultdict来设计一个计数器,例如计算文字中每个字母出现的次数:
 57 from collections import defaultdict
 58 from operator import itemgetter
 59 def count(text):
 60     counter=defaultdict(int)
 61     for c in text:
 62         counter[c] += 1
 63     return counter.items()
 64 text='You right brain has nothing left'
 65 for c,n in sorted(count(text),key=itemgetter(0)):
 66     print(c,':',n)
 67     
 68 # Counter类
 69 # 实际上collections模块中就有个Counter类,可以满足刚才的计数需求:
 70 # 由于Counter本身是字典(dict)的子类,因此想要新增或删除键值,方式与字典都是相同的
 71 from collections import Counter
 72 c=Counter('Your right brain has nothing left.')
 73 print(c)
 74 print(list(c.elements()))
 75 # 反过来运用也可以指定一个字典给Counter,它会按字典中值的指定创建对应数量的键:
 76 c=Counter({'Justin':4,'Monica':3,'Irene':2})
 77 print(list(c.elements()))
 78 c['Justin']=5
 79 print(list(c.elements()))
 80 
 81 # ChainMap类
 82 # 如果有多个字典对象想要把它们合并在一起,可以使用collections的ChainMap来达到目的:
 83 from collections import ChainMap
 84 custs1={'A':'Justin','B':'Monica'}
 85 custs2={'C':'Irene','D':'caterpillar'}
 86 custs=ChainMap(custs1,custs2)
 87 print(custs)
 88 # ChainMap({'A': 'Justin', 'B': 'Monica'}, {'C': 'Irene', 'D': 'caterpillar'})
 89 custs=custs.new_child({'X':'monica'})
 90 print(custs)
 91 # ChainMap({'X': 'monica'}, {'A': 'Justin', 'B': 'Monica'}, {'C': 'Irene', 'D': 'caterpillar'})
 92 print(custs.parents)
 93 # ChainMap({'A': 'Justin', 'B': 'Monica'}, {'C': 'Irene', 'D': 'caterpillar'})

from collections import ChainMap
baseline={'music':'math','art':'rembrante'}
adjustments={'art':'von gogh','oper':'carmen'}
print(list(ChainMap(adjustments,baseline)))


94 95 # UserList、UserDict、UserString类 96 # 如果只是想基于字符串、列表、字典等行为(或操作)增加一些自己的方法定义,那么可以使用collectinos模块的UserString、UserList、UserDict, 97 # 它们分别是Sequence、MutableSequence、Mutablepapping的子类 98 # 举个例子来说,虽然Python中不常见到方法链(Method chain)操作,不过下面故意实现了一个可进行方法链操作的MthChainList类 99 # 在某些程序设计语言中,这些链状操作是很受欢迎的方式 100 from collections import UserList 101 class MthChainList(UserList): 102 def filter(self,predicate): 103 return MthChainList(elem for elem in self if predicate(elem)) 104 def map(self,mapper): 105 return MthChainList(mapper(elem) for elem in self) 106 def for_each(self,action): 107 for elem in self: 108 action(elem) 109 lt=MthChainList(['a','B','c','d','E','f','G']) 110 lt.filter(str.islower).map(str.upper).for_each(print)

 

posted on 2019-03-21 22:16  larken  阅读(202)  评论(0编辑  收藏  举报