collections module you must know

Keywords: Python Lambda

Let's first look at the methods in the collections module:

__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
            'UserString', 'Counter', 'OrderedDict', 'ChainMap']

In this chapter, we only introduce methods other than UserDict/UserList/UserString. As for these three methods, we use them to inherit and implement the structure you want.
namedtuple: factory function used to create a tuple subclass with named fields

#For example, we want to construct a card class
Card=namedtuple('Card',[rank,suit])    #Equivalent to namedtuple('Card ', (rank,suit))
c1=Card('A','Heart')
c2=Card('K','Spade')
print(c1.rank)    #A
print(c1.suit)    #Heart
print(c1.rank)    #B
print(c1.suit)    #Spade
#To change the properties of an object, you can use the object. Replace (property = value) method to change the value of the created object
#_replace can pass in a dict

Deque: list like container, with quick append and pop-up classes at both ends, for creating a single view of multiple mappings (thread safe)

#Inside is a single letter array
a=deque("str")
a.appendleft("a")    #Insert data in the header
a.append("b")    #Insert data at the end
a.count("a")    #View the number of characters
a.insert(2,"y")    #Insert values based on index
a.clear()    #Clear double ended queue

defaultdict: multi value dictionary

dict1=defaultdict(list/dict/set/lambda :"None")
dict1['a'].add(1)    #Take set as an example
print(dict1)    #defaultdict(<class 'set'>, {'a': {1}})
print(dict1['b'])    #None, that's what lambda does

OrderedDict: keeps the order in which elements are inserted. The structure is a two-way linked list

#dict is also ordered by default in Python 3, but the methods are limited
od=OrderedDict([("name","jim"),("age",19),("sex","male")])
od.setdefault("high",178)    #Add a set of data, or use od["high"]=178
od.move_to_end('name')    #Place name group at the end

for i in od.items():
    print(i)    
#('name', 'jim')
#('age', 19)
#('sex ','male')
#('high', 178)

Counter: counter, a dictionary at the bottom

c=Counter()    #You can directly Counter("measure shipping") so that there is no loop
for i in "measure shishiyong":
    c[i]=c[i]+1
print(c)    
#Counter({'s': 2, 'h': 2, 'i': 2, 'test': 1, 'y': 1, 'o': 1, 'n': 1, 'g': 1})
print(c.most_common(3))    #Three elements with the most occurrences
#[('s', 2), ('h', 2), ('i', 2)]
#c ['element'] view the number of occurrences of an element
#c.update(list/str) can add elements
#Counter can operate with + / -

ChainMap: merge multiple dictionaries

dict1={'name':'jim','age':21}
dict2={'high':175,'gender':'male'}

new_dict=ChainMap(dict1,dict2)
print(new_dict)    #ChainMap({'name': 'jim', 'age': 21}, {'high': 175, 'gender': 'male'})
#The key value pairs in the previous dict will not be merged again. You can also use the update() method to
#The original dictionary is updated to the new dictionary, but the difference with direct merge is that update will recreate the new dictionary and update and delete the original dictionary
#Data does not affect the new dictionary

Posted by daniel244rock on Sun, 01 Dec 2019 00:03:21 -0800