Learn Python collections every day

Source: Internet
Author: User

Learn Python collections every day
Learn Python collections every day

Based on the built-in data types (dict, list, set, and tuple), the collections module provides several additional data types: ChainMap, Counter, deque, defaultdict, namedtuple, and OrderedDict.

ChainMap

ChainMap is a new feature of python3. It is used to form multiple maps into a new unit (the original map structure still exists, similar to the fact that these maps exist in a list ), this is much faster than creating a map and adding other maps with update. ChainMap can be used to simulate nested scenes and is mostly used in templates.

ChainMap supports all operations of a common map. The following describes its features:

# Create a ChainMap and Its Structure In [2]: from collections import ChainMapIn [3]: m1 = {'color': 'red', 'user ': 'users'} In [4]: m2 = {'name': 'drfish ', 'age': '18'} In [5]: chainMap = ChainMap (m1, m2) In [6]: print (chainMap. items () ItemsView (ChainMap ({'user': 'guest ', 'color': 'red'}, {'age': '18', 'name ': 'drfish '}) # obtain the element In ChainMap In [7]: print (chainMap. get ('name') drfishIn [8]: print (chainMap. get ('not') None # Add mapIn [9]: m3 = {'data': '1-6'} In [10]: chainMap = chainMap. new_child (m3) In [11]: print (chainMap. items () ItemsView (ChainMap ({'data': '1-6'}, {'user': 'guest ', 'color': 'red '}, {'age': '18', 'name': 'drfish '}) # parents attribute In [12]: print (chainMap. parents) ChainMap ({'user': 'guest ', 'color': 'red'}, {'age': '18', 'name': 'drfish '}) in [13]: print (chainMap. parents. parents) ChainMap ({'age': '18', 'name': 'drfish '}) In [14]: print (chainMap. parents. parents. parents) ChainMap ({}) # maps attributes In [15]: chainMap. mapsOut [15]: [{'data': '1-6'}, {'color': 'red', 'user': 'guest '}, {'age': '18', 'name': 'drfish '}]
Multiple maps can be input to initialize ChainMap. If the parameter is null, an empty map is automatically added to obtain the key. If the key does not exist, the system returns None. You can use the net_child () method to add a map, the new map is added to the ChainMap instance after the first map is removed from the previous parents attribute. Counter

Counter is a simple Counter, which is very convenient to use.

Initialization

Counter initialization supports multiple forms

In[18]: from collections import CounterIn[19]: c = Counter()In[20]: c = Counter('hello')In[21]: c = Counter({'a':3,'b':19})In[22]: c = Counter(cats=2,dogs=1)In[23]: cOut[23]: Counter({'cats': 2, 'dogs': 1})

Counter returns 0 for nonexistent elements. If you want to delete it, del:

In[23]: cOut[23]: Counter({'cats': 2, 'dogs': 1})In[24]: c['birds']Out[24]: 0In[25]: del c['cats']In[26]: cOut[26]: Counter({'dogs': 1})

The elements () method returns all elements. If there are a few elements, several are returned. The most_common (n) method can return the first n elements and the number of them:

In[29]: c = Counter(a=4, b=2, c=0, d=-2)In[30]: list(c.elements())Out[30]: ['a', 'a', 'a', 'a', 'b', 'b']In[33]: c.most_common(1)Out[33]: [('a', 3)]

Different Counter operations can also be performed. After the subtract () method is subtracted, it will affect the caller;&The operation indicates taking one of the two smaller ones (if only one Counter exists, no result set exists ),|The number of operations is large.

In[46]: c = Counter(a=13, b=11)In[47]: d = Counter(a=1, b=2)In[48]: c.subtract(d)In[49]: cOut[49]: Counter({'a': 12, 'b': 9})In[51]: c+dOut[51]: Counter({'a': 13, 'b': 11})In[52]: c-dOut[52]: Counter({'a': 11, 'b': 7})In[54]: c&dOut[54]: Counter({'a': 1, 'b': 2})In[55]: c|dOut[55]: Counter({'a': 12, 'b': 9})

Note: When performing an operation, if the number is negative, it will be ignored directly.

Deque

Deque is a dual-end queue, which is very similar to list, but you can add and delete elements to the left of list at the same time:

In[72]: dq = deque('abd')In[73]: dqOut[73]: deque(['a', 'b', 'd'])In[74]: dq.append('1')In[75]: dq.appendleft('-1')In[76]: dqOut[76]: deque(['-1', 'a', 'b', 'd', '1'])In[77]: dq.popleft()Out[77]: '-1'In[78]: dq.extendleft("hello")In[79]: dqOut[79]: deque(['o', 'l', 'l', 'e', 'h', 'a', 'b', 'd', '1'])

Note that the extendleft (x) method is equivalent to flipping x first and then adding it to the front-end of the list. The rotate method can be used to move the elements in the queue forward or backward:

In[82]: dq=deque("12345")In[83]: dqOut[83]: deque(['1', '2', '3', '4', '5'])In[84]: dq.rotate(2)In[85]: dqOut[85]: deque(['4', '5', '1', '2', '3'])In[86]: dq.rotate(-4)In[87]: dqOut[87]: deque(['3', '4', '5', '1', '2'])
Defaultdict

Defaultdict adds a default factory to a common dict so that a value of the corresponding type is automatically generated if the key does not exist:

In[88]: from collections import defaultdictIn[89]: d = defaultdict(int)In[90]: d['a']Out[90]: 0In[91]: d = defaultdict(dict)In[92]: d['a']Out[92]: {}

If the default factory is not added during initialization, The KeyError is also thrown:

In[93]: d = defaultdict()In[94]: d['a']Traceback (most recent call last):    d['a']KeyError: 'a'
Namedtuple

Namedtuple is the enhanced version of tuple. The biggest function is to set an alias for the value at each position of the tuple, increasing the readability of the program:

In[95]: from collections import namedtupleIn[96]: Point = namedtuple("Point",['x','y'])In[97]: p = Point(1,2)In[98]: p.xOut[98]: 1In[99]: p.yOut[99]: 2

Because an alias is used to form a dictionary, namedtuple can be converted to the OrderedDict to be introduced below. It can also be converted to the following dictionary:

In[100]: p._asdict()Out[100]: OrderedDict([('x', 1), ('y', 2)])In[101]: d = {'x':11,'y':22}In[102]: Point(**d)Out[102]: Point(x=11, y=22)

Namedtuple also provides methods to obtain all domains and modify the corresponding values:

In[108]: pOut[108]: Point(x=1, y=2)In[109]: p._fieldsOut[109]: ('x', 'y')In[110]: p._replace(x=10)Out[110]: Point(x=10, y=2)
OrderedDict

Dict is disordered, but sometimes we want the dictionary to be ordered. OrderedDict provides this service, and the key-value pairs in OrderedDict are stored in the order they joined:

In[130]: fruit=(('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1))In[131]: d = dict(fruit)In[132]: dOut[132]: {'apple': 4, 'banana': 3, 'orange': 2, 'pear': 1}In[135]: d.popitem()Out[135]: ('apple', 4)In[136]: d.popitem()Out[136]: ('orange', 2)In[137]: d.popitem()Out[137]: ('banana', 3)In[138]: d.popitem()Out[138]: ('pear', 1)In[133]: od = OrderedDict(fruit)In[134]: odOut[134]: OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])In[139]: od.popitem()Out[139]: ('pear', 1)In[140]: od.popitem()Out[140]: ('orange', 2)In[141]: od.popitem()Out[141]: ('banana', 3)In[142]: od.popitem()Out[142]: ('apple', 4)

Note: In OrderedDict, The popitem (last = True) function is added first if the last value is set to False.

You can use the move_to_end (key, last = True) function to change the position of the key-value pair. If it is True, it is moved to the end. If it is False, it is moved to the beginning:

In[146]: odOut[146]: OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])In[147]: od.move_to_end('apple')In[148]: odOut[148]: OrderedDict([('banana', 3), ('orange', 2), ('pear', 1), ('apple', 4)])In[149]: od.move_to_end('pear',False)In[150]: odOut[150]: OrderedDict([('pear', 1), ('banana', 3), ('orange', 2), ('apple', 4)])
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.