Python模块

来源:互联网 发布:fastdfs nginx 400 编辑:程序博客网 时间:2024/05/29 10:07

collections的常用类型有:
计数器(Counter)
双向队列(deque)
默认字典(defaultdict)
有序字典(OrderedDict)
可命名元组(namedtuple)

Counter()

Counter 作为字典(dict)的一个子类用来进行hashtable计数,将元素进行数量统计、计数后返回一个字典,键值为元素:值为元素个数

s = 'abcbcaccbbad'  l = ['a','b','c','c','a','b','b']  d = {'2': 3, '3': 2, '17': 2}  # Counter 获取各元素的个数,返回字典  print(Counter(s))   # Counter({'c': 4, 'b': 4, 'a': 3})  print(Counter(l))   # Counter({'b': 3, 'a': 2, 'c': 2})  
  • most_common(n)
    如果省略n或者None,most_common()返回计数器中的所有元素。具有相同数量的元素是任意排序的:
# most_common(int) 按照元素出现的次数进行从高到低的排序,返回前int个元素的字典  m1 = Counter(s)  print(m1)                 # Counter({'c': 4, 'b': 4, 'a': 3, 'd': 1})  print(m1.most_common(3))  # [('c', 4), ('b', 4), ('a', 3)]  
>>> Counter('abracadabra').most_common(3)[('a', 5), ('r', 2), ('b', 2)]
  • elements()
# elements 返回经过计数器Counter后的元素,返回的是一个迭代器  e1 = Counter(s)  print(''.join(sorted(e1.elements())))  # aaabbbbcccc  e2 = Counter(d)  print(sorted(e2.elements()))  # ['17', '17', '2', '2', '2', '3', '3'] 字典返回value个key  
>>> c = Counter(a=4, b=2, c=0, d=-2)>>> list(c.elements())['a', 'a', 'a', 'a', 'b', 'b']
  • update()
# updateset集合的update一样,对集合进行并集更新  u1 = Counter(s)  u1.update('123a')  print(u1)  # Counter({'a': 4, 'c': 4, 'b': 4, '1': 1, '3': 1, '2': 1})  
  • substract()
# substract 和update类似,只是update是做加法,substract做减法,从另一个集合中减去本集合的元素,  sub1 = 'which'  sub2 = 'whatw'  subset = Counter(sub1)  print(subset)   # Counter({'h': 2, 'i': 1, 'c': 1, 'w': 1})  subset.subtract(Counter(sub2))  print(subset)   # Counter({'c': 1, 'i': 1, 'h': 1, 'a': -1, 't': -1, 'w': -1}) sub1中的h变为2,sub2中h为1,减完以后为1  
  • iteritems()
    与字典dict的items类似,返回由Counter生成的字典的所有item,只是在Counter中此方法返回的是一个迭代器,而不是列表

OrderedDict ()

OrderDict 叫做有序字典,也是字典类型(dict)的一个子类,是对字典的一个补充,由于有序字典记住其插入顺序,因此可以与排序一起使用以排序排序的字典:

>>> # regular unsorted dictionary>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}>>> # dictionary sorted by key>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])>>> # dictionary sorted by value>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])>>> # dictionary sorted by length of the key string>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])

deque()

deque 包含在文件_collections.py中,属于高性能的数据结构(High performance data structures)之一.可以从两端添加和删除元素,常用的结构是它的简化版。

append:队列右边添加元素
appendleft:队列左边添加元素
clear:清空队列中的所有元素
count:count(value) 返回队列中包含value的个数,结果类型为 integer
extend:extend 队列右边扩展,可以是列表、元组或字典,如果是字典则将字典的key加入到deque
extendleft:extendleft 同extend, 在左边扩展
pop:pop 移除并且返回队列右边的元素
popleft:popleft 移除并且返回队列左边的元素
remove:remove(value) 移除队列第一个出现的元素(从左往右开始的第一次出现的元素value)
reverse: 队列的所有元素进行反转
rotate:rotate(n) 对队列的数进行移动,若n<0,则往左移动即将左边的第一个移动到最后,移动n次,n>0 往右移动

>>> from collections import deque>>> d = deque('ghi')                 # make a new deque with three items>>> for elem in d:                   # iterate over the deque's elements...     print elem.upper()GHI>>> d.append('j')                    # add a new entry to the right side>>> d.appendleft('f')                # add a new entry to the left side>>> d                                # show the representation of the dequedeque(['f', 'g', 'h', 'i', 'j'])>>> d.pop()                          # return and remove the rightmost item'j'>>> d.popleft()                      # return and remove the leftmost item'f'>>> list(d)                          # list the contents of the deque['g', 'h', 'i']>>> d[0]                             # peek at leftmost item'g'>>> d[-1]                            # peek at rightmost item'i'>>> list(reversed(d))                # list the contents of a deque in reverse['i', 'h', 'g']>>> 'h' in d                         # search the dequeTrue>>> d.extend('jkl')                  # add multiple elements at once>>> ddeque(['g', 'h', 'i', 'j', 'k', 'l'])>>> d.rotate(1)                      # right rotation>>> ddeque(['l', 'g', 'h', 'i', 'j', 'k'])>>> d.rotate(-1)                     # left rotation>>> ddeque(['g', 'h', 'i', 'j', 'k', 'l'])>>> deque(reversed(d))               # make a new deque in reverse orderdeque(['l', 'k', 'j', 'i', 'h', 'g'])>>> d.clear()                        # empty the deque>>> d.pop()                          # cannot pop from an empty dequeTraceback (most recent call last):  File "<pyshell#6>", line 1, in -toplevel-    d.pop()IndexError: pop from an empty deque>>> d.extendleft('abc')              # extendleft() reverses the input order>>> ddeque(['c', 'b', 'a'])