collections module provides data structures other than the common data structures python, into several
- namedtuple () : Special tuple subclass can use to access the names and subscript
- the deque : deque, from the other side can be quickly and additional objects Release
- Counter : a counter for counting the main
- OrderedDict : ordered dictionary
- defaultdict : Dictionary with default values
- ChainMap: dictionary-like containers, a plurality of maps which set to a view
namedtuple name suggests, is a tuple with the name, there is a dictionary-like access methods, accessed through the following yourtuple.key
#!/usr/bin/python3 # -*- coding: utf-8 -*- from collections import namedtuple persons = [ ('男', '1988-04-11', '张三'), ('女', '1993-03-26', '李四'), ('男', '1990-06-02', '王五') ] Person = namedtuple('person', ['sex', 'birthday', 'name']) # Person = namedtuple('person', ('sex', 'birthday', 'name')) # Person = namedtuple('person', 'sex, birthday, name') # Person = namedtuple('person', 'sex birthday name') if __name__ == '__main__': for person in persons: person = Person._make (Person) # person = Person (person [0 # can be created _make (tuple type) or calls the new method Print (Person) print(person.name, person[0])
output:
person (sex = 'M', birthday = '1988-04-11', name = ' Joe Smith') Zhang M person (sex = 'F', birthday = '1993-03-26', name = ' John Doe ') John Doe female person (sex =' male ', birthday =' 1990-06-02 ', name =' king of five ') Wang five men
Note: namedtuple (parm1, parm2)
parm1 names of the constructor, parm2 may be a list, tuples, or string
Parm2 number of elements and the number of parameters that need to pass the same parameters, such as: Person ( 'M', '1988-04-11', 'John Doe', '1383333333') will be given Expected 3 arguments, got 4
and
collections.deque
Returns a new deque object gain access to the ends of the queues, thread safety support, for adding (the append) from both ends or popped (POP), complexity of O (1).
Although list
the object supports a similar operation, the complex group O (n) the greater the consumption increases as the length of the list
if the default maxlen None, it can grow to any length. Otherwise, deque would be limited to a specified maximum length. Once defined deque full length, when a new entry is added, the same number of items on the pop-up from the other end.
Supported methods:
- append (x): x is added to the right
- appendleft (x): x is added to the left
- clear (): clear all the elements, the length becomes 0
- copy (): Creates a shallow copy
- count (x): calculated number is equal to the queue element x
- extend (iterable): additive element in the queue right iterable
- extendleft (iterable): additive element in the queue iterable left Note: when adding the left will turn the order to add the parameter iterable
- index (x [, start [, stop]]): Returns the x-th element (from start to start, before the stop). Returns the first match, if not found, raising ValueError.
- insert (i, x): i is inserted at a position x. Note: If you insert will lead to a long deque beyond the length limit maxlen, then it rises a IndexError.
- pop (): remove elements of the far right
- popleft (): remove the leftmost element
- remove (value): Remove the first one found value. Does not throw ValueError
- reverse (): The deque in reverse order. Return None.
- maxlen: the maximum queue length, was not limited None.
from collections import deque d = deque(maxlen=10) print(d) d.extend('hello world') [i.upper() for i in d] ['P', 'Y', 'T', 'H', 'O', 'N'] d.append('e') d.appendleft('f') print(d)
output:
deque([], maxlen=10)
deque(['f', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'], maxlen=10)
Counter
Counter is a dict subclass primarily used to access your target frequency counts.
Common methods:
- elements (): returns an iterator, the number of repeated calculations for each element, an element if the count is less than 1, will be ignored.
- most_common ([n]): returns a list of the n most frequently accessed to provide an element and counting ChainMap
- subtract ([iterable-or-mapping]): iterative subtracting elements from the object, the input and output may be 0 or negative
- update ([iterable-or-mapping]): iteration count objects or add elements from another map from the object (or counter).
import collections print(collections.Counter('hello world')) # 统计单词数 print(collections.Counter('hello world hello world hello nihao'.split()))
output:
Counter({'l': 3, 'o': 2, 'r': 1, 'w': 1, 'h': 1, 'd': 1, 'e': 1, ' ': 1})
Counter({'hello': 3, 'world': 2, 'nihao': 1})
OrderedDict
Python dictionary ordering of the keys of the disorder, the sequential control is not added.
collections.OrderedDict
Add reserved dictionary object they order.
from collections import OrderedDict demo_dict = {"a": 1, "b": 2, "c": 3} order_dict = OrderedDict(demo_dict) print (demo_dict, order_dict) demo_dict['s'] = 5 print (demo_dict) order_dict['s'] = 5 print(order_dict)
output:
{'b': 2, 'a': 1, 'c': 3} OrderedDict([('b', 2), ('a', 1), ('c', 3)])
{'s': 5, 'b': 2, 'a': 1, 'c': 3}
OrderedDict([('b', 2), ('a', 1), ('c', 3), ('s', 5)])
defaultdict
defaultdict(factory)
Provide a default value is not the key dictionary. Argument should be a function that returns a default value when no call parameters. If you do not pass anything, it defaults to None
from collections import defaultdict demo_dict = {} try: print(demo_dict['s']) # KeyError except: pass default_dict = defaultdict(str) default_dict['s'] print(demo_dict) print(default_dict)
output:
{}
defaultdict(<class 'str'>, {'s': ''})
ChainMap
ChainMap sum equivalent to more than a dictionary.
from collections import ChainMap d1 = {"a": 1, "b": 2, "aa": 1} d2 = {"aa": 11, "bb": 22, "b": 3} sd = ChainMap(d1, d2) print(sd) for k, v in sd.items(): print(k, v)
output:
ChainMap({'aa': 1, 'a': 1, 'b': 2}, {'b':3, 'bb': 22, 'aa': 11})
1 2 of
a 1 .
B 2
Bb 22 by
aa 1
Note: the same key value, behind the front cover.
Reference: Author: onemore
Source: https://www.cnblogs.com/dianel/
Original 2: http://www.zlovezl.cn/articles/collections-in-python/