本文共 3601 字,大约阅读时间需要 12 分钟。
1、计数器(counter)
Counter是对字典类型的补充,用于追踪值出现的次数。
提示:具备字典的所有功能和自己地功能
示例①
collectionsc1 =collections.Counter()c1
运行结果:
D:\Python27\python.exe C:/Users/ryan/PycharmProjects/s11day3/coll.py
Counter({'c': 4, 'd': 4, 'q': 4, 'a': 3, 'f': 3, 'e': 2})常见方法:
>>> c = Counter('abcdeabcdabcaba') # count elements from a string >>> c.most_common(3) # three most common elements [('a', 5), ('b', 4), ('c', 3)] >>> sorted(c) # list all unique elements ['a', 'b', 'c', 'd', 'e'] >>> ''.join(sorted(c.elements())) # list elements with repetitions 'aaaaabbbbcccdde' >>> sum(c.values()) # total of all counts 15 >>> c['a'] # count of letter 'a' 5 >>> for elem in 'shazam': # update counts from an iterable ... c[elem] += 1 # by adding 1 to each element's cou >>> c['a'] # now there are seven 'a' 7 >>> del c['b'] # remove all 'b' >>> c['b'] # now there are zero 'b' 0 >>> d = Counter('simsalabim') # make another counter >>> c.update(d) # add in the second counter >>> c['a'] # now there are nine 'a' 9 >>> c.clear() # empty the counter >>> c Counter() Note: If a count is set to zero or reduced to zero, it will remain in the counter until the entry is deleted or the counter is cleared: >>> c = Counter('aaabbc') >>> c['b'] -= 2 # reduce the count of 'b' by two >>> c.most_common() # 'b' is still in, but its count is zero [('a', 3), ('c', 1), ('b', 0)] '''
提示:element是一个迭代器,迭代器中数据只有通过循环来获取
如果计数器中没有某个元素。则返回0
提示:更新计数器,其实就是增加,原来没有的就新建,原来有的就自动加一
提示:相减,原来的计数器中的每一个元素的数量减去后面添加元素的数量
#!/usr/bin/env python # -*- coding:utf-8 -*- import collections list_001 = ['a','a','b','b','c',11,434,44,333,11,22,33,444,653,33,333,653] tuple_001 = ('a','b','c','a','b','c','c','c',122,122,3,3,3,3,3,5,5,5,5,6) c1 =collections.Counter('aaaddddeefffccccqqqq') c2 = collections.Counter(list_001) c3 = collections.Counter(tuple_001) print c1 print c2 print c3
Counter({'c': 4, 'd': 4, 'q': 4, 'a': 3, 'f': 3, 'e': 2})
Counter({'a': 2, 33: 2, 'b': 2, 11: 2, 333: 2, 653: 2, 'c': 1, 44: 1, 434: 1, 22: 1, 444: 1}) Counter({3: 5, 'c': 4, 5: 4, 'a': 2, 'b': 2, 122: 2, 6: 1})提示:计数器中的计数对象可以是字符串也可以是列表也可以是元组
2、计数器之有序字典ordereddict
有序字典是在字典里面维护了一个以键为元素的列表,由于字典是无序而列表时有序的,所以当打印有序字典的时候,就出现有序的排列:
collectionsO1 = collections.OrderedDict()O1[] = O1[] = O1[] = O1其实相当于在内部维护了一个列表:L = ['k1','k2','k3']那么当循环该列表的时候:for nu in L: print nu就会出现有序的nu值打印结果:OrderedDict([('k1', 1), ('k2', 2), ('k3', 3)])k1k2k3
总结:有序字典的里面没有特殊方法,跟一般字典的方法完全一致,如果说区别的话那就是输出键值对是有序的
3、计数器之默认字典
dic = {:}dic[].append() dic = {}dic.keys(): dic[] = dic[].append(): dic[] = []collectionsmy_dic = collections.defaultdict()
4、计数器之可命名元组
collectionsMytuple = collections.namedtuple([])new = Mytuple()newnew.xnew.y输出结果:Mytuple(x=1, y=2)12从以上结果可以看出语句Mytuple = collections.namedtuple('Mytuple',['x','y'])其实是创建了一个类似的字典,只要传值进去,就可以将x和y作为key与其值对应起来:dic = {'x':1,'y':2}
5、计数器之双向队列(一个线程安全的双向队列)
from collections import dequeq = deque()方法append()q.append(11)q.append(12)q.append(13)q.append(14)print q输出结果:deque([11, 12, 13, 14])方法pop()q.pop()print q输出结果:deque([11, 12, 13])方法popleft()q.popleft()print q输出结果deque([12, 13])
6、单向队列(先进先出IFIO,栈是先进后出,后进先出,两者正好相反)不在collections里面,而是在Queue模块中
from Queue import Queue#创建一个队列,里面存放10条数据q = Queue(10)print q#向队列q中存放至用方法put(),每执行一次就放入一个值q.put(1)q.put(2)q.put(3)#向队列q中拿值,用方法put(),每执行一次就拿出一个值q.get()q.get()
本文转自027ryan 51CTO博客,原文链接:http://blog.51cto.com/ucode/1716917,如需转载请自行联系原作者