collections
collections is a key and high-frequency module in daily work. Common types are:
Counter
Bidirectional queue (deque)
Default dictionary
Ordered dictionary
Named tuple
1. Counter
As a subclass of dictionary dicit (), Counter is used to count hashtable, count the number of elements, and return a dictionary after counting. The key value is the element and the value is the number of elements
Common methods:
most_common(int) | Sort the elements from high to low according to the number of occurrences, and return the dictionary of the first int elements |
elements | Returns the element after the calculator Counter, and returns an iterator |
update | Like the update of set, union update is performed on the set |
substract | It is similar to update, except that update adds and substract subtracts the elements of this set from another set |
iteritems | Returns all item s of the dictionary generated by Counter |
iterkeys | Returns all key s of the dictionary generated by Counter |
itervalues | Returns all value s of the dictionary generated by Counter |
Example:
#coding=utf-8 from collections import Counter str = "abcbcaccbbad" li = ["a","b","c","a","b","b"] d = {"1":3, "3":2, "17":2} #Counter gets the number of each element and returns the dictionary print ("Counter(s):", Counter(str)) print ("Counter(li):", Counter(li)) print ("Counter(d):", Counter(d)) #most_common(int) sorts elements from high to low according to the number of occurrences, and returns the dictionary of the first int elements d1 = Counter(str) print ("d1.most_common(2):",d1.most_common(2)) #elements returns the element after the Counter of the calculator, and an iterator is returned print ("sorted(d1.elements()):", sorted(d1.elements())) print ('''("".join(d1.elements())):''',"".join(d1.elements())) #If it is a dictionary, return value key d2 = Counter(d) print("If it is a dictionary, return value individual key:", sorted(d2.elements())) #Update is the same as the update of the set set, which performs union update on the set print ("d1.update("sas1"):",d1.update("sas1"))
>>>> Counter(s): Counter({'b': 4, 'c': 4, 'a': 3, 'd': 1})
>>>> Counter(li): Counter({'b': 3, 'a': 2, 'c': 1})
>>>> Counter(d): Counter({'1': 3, '3': 2, '17': 2})
>>>> d1.most_common(2): [('b', 4), ('c', 4)]
>>>> sorted(d1.elements()): ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'd']
>>>> ("".join(d1.elements())): aaabbbbccccd
>>>> ['1', '1', '1', '17', '17', '3', '3']
2. deque
deque is one of the high-performance data structures. The common methods are as follows:
append | Add elements to the right of the queue |
appendleft | Add elements to the left of the queue |
clear | Clear all elements in the queue |
count | Returns the number of value s in the queue |
extend | The extension on the right side of the queue can be a list, tuple or dictionary. If it is a dictionary, add the key of the dictionary to deque |
extendleft | Same as extend, extend on the left |
pop | Removes and returns the element to the right of the queue |
popleft | Removes and returns the element to the left of the queue |
remove(value) | Remove the first element in the queue |
reverse | All elements of the queue are reversed |
rotate(n) | Move the number of queues |
3. defaultdict
The default dictionary, a subclass of the dictionary, inherits the methods of all dictionaries. When defining and initializing the default dictionary, you must specify that the dictionary value has the default type
dic = defaultdict(dict) dic["k1"].update({"asdsa":"123"}) print (dic) >>> defaultdict(<class 'dict'>, {'k1': {'asdsa': '123'}})
Note: the dictionary dic defines the value as the dictionary type when it is defined. Although there is no key value k1 in the dictionary, the update method of the dictionary can still be executed. This operation method cannot be realized in the traditional dictionary type. The value can be updated only after assignment, otherwise an error will be reported.
4. OrderedDict
Ordered dictionary is also a subclass of dictionary
Traditional methods for dictionary sorting
#Defining traditional dictionaries dic1 = dict() # Add dictionary contents in order dic1['a'] = '123' dic1['b'] = 'jjj' dic1['c'] = '394' dic1['d'] = '999' print(dic1) # Result: {'a':'123 ',' C ':'394', 'B':'jjj ','d':'999 '} # sort dic1_key_list = [] for k in dic1.keys(): dic1_key_list.append(k) dic1_key_list.sort() for key in dic1_key_list: print('dic1 Dictionary sorting results %s:%s' %(key,dic1[key]))
Sorting dictionaries using OrderedDict
#Define ordered dictionary dic2 = OrderedDict() dic2['a'] = '123' dic2['b'] = 'jjj' dic2['c'] = 'abc' dic2['d'] = '999' for k, v in dic2.iteritems(): print('Ordered Dictionary:%s:%s' %(k,v))
5. namedtuple
Namedtuple is created by its own class factory namedtuple(), instead of being initialized by tuples in the table. The parameters for creating a class through namedtuple include the class name and a string containing the element name
Examples of common methods:
#coding=utf-8 from collections import namedtuple p = namedtuple("person", "name,age,sex") print (type(p)) zhanglin = p("zhanglin",30,"male") print(zhanglin) print(zhanglin.name,zhanglin.age)
>>> <class 'type'>
>>> person(name='zhanglin', age=30, sex='male')
>>> zhanglin 30
The rename parameter uses
When using namedtuple() to create a class, the passed member attribute parameter name cannot be illegal (cannot be duplicate or system identifier), otherwise an error will be reported
try: pp = namedtuple("person","name,age,class,sex") print(pp._fields) lili = pp("lili",20,"aa","male") except Exception as e: print("error",e)
>>> error Type names and field names cannot be a keyword: 'class'
The input error is beyond our control. If namedtuple provides the parameter rename=True, the system will automatically replace the wrong parameter name by "underline + parameter index"
try: pp = namedtuple("person","name,age,class,sex",rename=True) print(pp._fields) lili = pp("lili",20,"aa","male") except Exception as e: print("error",e)
>>> ('name', 'age', '_2', 'sex')
itertoos
heap