上QQ阅读APP看书,第一时间看更新
Specialized data containers from the collections module
Every data structure has its shortcomings. There is no single collection that can suit every problem, and four basic types of them (tuple, list, set, and dictionary) is still not a wide range of choices. These are the most basic and important collections that have a dedicated literal syntax. Fortunately, Python provides far more options in its standard library through the collections built-in module. Here are the most important universal data containers provided by this module:
- namedtuple(): This is a factory function for creating tuple subclasses whose indexes can be accessed as named attributes
- deque: This is a double-ended queue—a list-like generalization of stacks and queues with fast appends and pops on both ends
- ChainMap: This is a dictionary-like class to create a single view of multiple mappings
- Counter: This is a dictionary subclass for counting hashable objects
- OrderedDict: This is a dictionary subclass that preserves the order that the entries were added in
- defaultdict: This is a dictionary subclass that can supply missing values using a user-defined factory function
More details on selected collections from the collections module and some advice on where it is worth using them is provided in Chapter 14, Optimization – Some Powerful Techniques.