I. namedtuple
namedtuple()
function is a factory function that returns a subclass that inherits from the tuple class and has the name, which is the name you pass to thenamedtuple()
of the first parameter of the subclass. An instance of this subclass acts like a normal tuple, but also provides easy access to properties.
namedtuple
is an easy way to define small and immutable data classes.
from collections import namedtuple # Create a User of type namedtuple with the attributes name and age. User = namedtuple('User', ['name', 'age']) # Create a User object user = User(name='user1', age=23) print() # Output: user1 print() # exports:23
II. deque
deque
(bi-directional queuing) is a method fromcollections
Container for modules, which provides the ability to efficiently and quickly add and remove elements from the left and right ends.
from collections import deque # Create a deque d = deque(['a', 'b', 'c']) # Add elements from the right end ('d') # d is now deque(['a', 'b', 'c', 'd']) # Add elements from the left end ('e') # d is now deque(['e', 'a', 'b', 'c', 'd']) # Remove elements from the right end () # Return 'd', d is now deque(['e', 'a', 'b', 'c']) # Remove elements from the left end () # come (or go) back 'e', dNow.deque(['a', 'b', 'c'])
III. Counter
collections
modularCounter
class is a simple counter that can be used, for example, to count the number of characters:
from collections import Counter c = Counter('hello world') # Create from an iterable object print(c) # exports Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
Counter
object has a useful methodmost_common(n)
, which returns a list of the n elements with the highest count, each of which is a tuple whose first element is the element itself and whose second element is the count of the element.
IV. defaultdict
defaultdict
is a subclass of dict that accepts a factory function as a default value and can instantiate a value as the default when the key to look up does not exist.
from collections import defaultdict # Use list(list) as default_factory and return an empty list when the key does not exist. dd = defaultdict(list) # Add a key-value pair dd['dogs'].append('Rufus') dd['dogs'].append('Kathrin') dd['dogs'].append('Mr Sniffles') print(dd['dogs']) # exports: ['Rufus', 'Kathrin', 'Mr Sniffles']
V. OrderedDict
OrderedDict
is a subclass of dict that remembers the order in which elements are inserted. Prior to Python 3.7, plain dict did not guarantee the order of key-value pairs, and theOrderedDict
then the elements are arranged in the order in which they were inserted.
Starting with Python 3.7, dict also maintains the insertion order, but theOrderedDict
still has its properties, such as rearranging the order of the dictionary.
from collections import OrderedDict d = OrderedDict() d['first'] = 1 d['second'] = 2 d['third'] = 3 d['last'] = 4 # exports "first 1", "second 2", "third 3", "last 4" for key in d: print(key, d[key])
VI. Conclusion
collections
There are other useful tools included in the module, such as theChainMap
、UserDict
、UserList
etc. These are very useful collection classes. Using and understanding these data structures can make us more comfortable in programming and our code more efficient and clear.
These above arecollections
Some of the most commonly used data structures in the module, understanding and skillfully using these tools can greatly improve the efficiency of our programming. Hopefully this article will help you gain a deeper understanding of Python'scollections
modules to be able to program better with Python.
Above is Python built-in module collections to achieve the details of the special container data type, more information about Python collections module please pay attention to my other related articles!