Collections is a collection module built in Python and provides many useful collection classes. 1. counter is a simple Counter, for example, count the number of characters: & gt; importcollections & gt; objcollections. counter (applebanana) & gt; print (obj) Counter ({a: 4, n: 2, p: 2, e: 1, l: 1, b: 1}) collections is a collection module built in Python and provides many useful collection classes. 1. Counter is a simple Counter, for example, count the number of characters: >>> import
Collections >>> obj =
Collections. Counter ('applebana') >>> print (obj) Counter ({'a': 4, 'n ':
2, 'P': 2, 'E': 1, 'L': 1, 'B': 1}) 2. when OrderedDict ordered dictionary uses dict, keys are unordered. During the iteration of dict, we cannot determine the Key order. To keep the Key order, use OrderedDict:> od =
Collections. OrderedDict () >>> od ['K2']
= 'K2'> od ['k1 '] =
'K1 '> odOrderedDict ([('K2 ',
'K2'), ('k1 ', 'k1')]) or> od =
Collections. OrderedDict ([('K2', 'V2'), ('k1 ', 'v1')]) >>> odOrderedDict ([('K2 ',
'V2'), ('k1 ', 'v1')]) 3. defaultdict default dictionary Sets a default type for the dictionary value import collectionsnum =
[,] # Add the default list type my_dic = for the value of my_dic Dictionary
Collections. defaultdict (list) for I in num: if I> 66: my_dic ['k1 ']. append (I) else: my_dic ['K2']. append (I) print (my_dic) 4. namedtuple can be named as the ancestor namedtuple. it is a function used to create a custom tuple object, and defines the number of tuple elements. It can also reference an element of tuple with attributes rather than indexes. In this way, we can use namedtuple to easily define a data type. it has the immutability of tuple and can be referenced based on attributes. it is very convenient to use >>> person = collections. namedtuple ('pp ', ['name', 'age']) >>> p = person ('apple', 2) >>> print (p. name) >>> print (p. age) 5. when deque bidirectional queues use list to store data, index-based access elements are fast, but the insertion and deletion of elements is slow, because list is linear storage, when the data volume is large, insert and delete operations are inefficient. Deque is a bidirectional list for efficient insert and delete operations. it is applicable to queues and stacks: >>> dli =
Collections. deque ([1, 2, 3]) >>>
Dli. append (4) >>> dlideque ([1, 2, 3, 4]) >>>
Dli. appendleft (5) # appendleft insert data to the left >>> dlideque ([5, 1, 2, 3, 4]) 6. queue single queue (in the queue module) import queueq = queue. queue () q. put (123) q. put (456) print (q. qsize () print (q. get () # q. get () extracts data from a single queue in order print (q. get ())
The above is the basic content of Python: Details of the collections module. For more information, see other related articles in the first PHP community!