Python Collections library introduction

Python Collections library introduction

namedtuple package

namedtuple can create objects similar to tuple, but the namedtuple class itself and the corresponding element can have a name, which is a bit similar to a normal class without methods.

from collections import namedtuple

# 定义一个namedtuple类型User,并包含name,sex和age属性。
User = namedtuple('User', ['name', 'sex', 'age'])

# 创建一个User对象
user = User(name='kongxx', sex='male', age=21)

# 也可以通过一个list来创建一个User对象,这里注意需要使用"_make"方法
user = User._make(['kongxx', 'male', 21])

print user
# User(name='user1', sex='male', age=21)

# 获取用户的属性
print user.name
print user.sex
print user.age

# 修改对象属性,注意要使用"_replace"方法
user = user._replace(age=22)
print user
# User(name='user1', sex='male', age=22)

# 将User对象转换成字典,注意要使用"_asdict"
print user._asdict()
# OrderedDict([('name', 'kongxx'), ('sex', 'male'), ('age', 22)])

deque bag

The basic operation of the internal two-way queue is as follows

  • Left and right element processing operations: append, appendleft, extend, extendleft, pop, popleft
  • Intermediate element operations: insert (insert at a certain position), remove (remove the specified value from the first occurrence, return ValueError if it does not exist)
  • The overall operation of the element: clear (empty the queue), copy (implement a shallow copy of the queue), count (count the number of an element in the queue), index (return the index of the first occurrence of the element from start to stop, there is no return ValueError), reverse (local reverse), rotate (circulate to the right, negative to left)
  • Magic function: + (similar to extend), +=, * (how many copies of the corresponding content to copy), *=, in, len, del (delete an element at a certain position), [] (acquire or assign a value according to the subscript ), () (passing in the iterable object to initialize the queue), comparison operation (==, >, <, >=, <= sequentially compare the elements of the two queues)
from collections import deque
d = deque([1,2,3])
d.extendleft(['a','b','c'])
print(d)

deque(['c', 'b', 'a', 1, 2, 3])

ChainMap package

hainMap 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 these maps are stored in a list), which is better than creating a new map and then using other maps Update is added much faster. ChainMap can be used to simulate nested scenarios, and it is mostly used in templates.

ChainMap supports all operations of ordinary map, the following mainly shows its characteristics:

# 新建ChainMap及它的结构
In[2]: from collections import ChainMap
In[3]: m1 = {'color': 'red', 'user': 'guest'}
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'}))

# 获取ChainMap中的元素
In[7]: print(chainMap.get('name'))
drfish
In[8]: print(chainMap.get('not'))
None

# 新增map
In[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属性
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属性
In[15]: chainMap.maps
Out[15]: 
[{'data': '1-6'},
 {'color': 'red', 'user': 'guest'},
 {'age': '18', 'name': 'drfish'}]

Counter bag

A subclass of dictionary that records the number of occurrences of hashable objects

First of all, Counter has multiple initialization methods

        >>> c = Counter()                           # a new, empty counter
        >>> c = Counter('gallahad')                 # a new counter from an iterable
        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
        >>> c = Counter(a=4, b=2)                   # a new counter from keyword args

 The main operation examples are as follows

    >>> 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 count
    >>> 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)]

Logical operation 

        >>> c = Counter('which')
        >>> c.subtract('witch')             # subtract elements from another iterable
        >>> c.subtract(Counter('watch'))    # subtract elements from another counter
        >>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
        0
        >>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
        -1

        >>> Counter('abbb') + Counter('bcc')
        Counter({'b': 4, 'c': 2, 'a': 1})

        >>> Counter('abbbc') - Counter('bccd')
        Counter({'b': 2, 'a': 1})

        >>> Counter('abbb') | Counter('bcc')
        Counter({'b': 3, 'c': 2, 'a': 1})

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})

OrderedDict 包

Provide an ordered dictionary, which can realize the traversal operation. The internal storage order is given according to the incoming order.

import collections
 
print 'Regular dictionary:'
d1={}
d1['a']='A'
d1['b']='B'
d1['c']='C'
 
d2={}
d2['c']='C'
d2['a']='A'
d2['b']='B'
 
print d1==d2
 
print '\nOrderedDict:'
d1=collections.OrderedDict()
d1['a']='A'
d1['b']='B'
d1['c']='C'
 
d2=collections.OrderedDict()
d2['c']='C'
d2['a']='A'
d2['b']='B'
 
print  d1==d2

defaultdict 包

Create a dictionary with default values, which are based on the factory function passed in

from collections import defaultdict

dict1 = defaultdict(int)
dict2 = defaultdict(set)
dict3 = defaultdict(str)
dict4 = defaultdict(list)
dict1[2] ='two'

print(dict1[1])
print(dict2[1])
print(dict3[1])
print(dict4[1])

'''
0
set()

[]
'''

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/a40850273/article/details/105727522