昨天用到了这个collections模块,挺好用的,这里记录下。
官网介绍:https://docs.python.org/3/library/collections.html
博客:廖雪峰的博客
这里介绍些好玩儿的例子。
namedtuple
collections.namedtuple(typename, field_names, *, verbose=False, rename=False, module=None)
Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful repr() method which lists the tuple contents in a name=value format.
namedtuple是一个工厂函数,返回一个自定义的tuple类,可读性更强些。
通常我们使用tuple的时候,像这样
我们是那个namedtuple就可以这样了
这样使用一个坐标位置,是不是可读性更强呢,而且用起来也很方便
我们可以看看这个Point是怎样定义的
下面还有个更好用的地方,我们再读取CSV或者数据库的时候,会返回结果集,这个时候用起来更方便,比如:
_make
deque
我们使用list的时候,用下标查找很快,数据量大的时候,插入删除比较慢,deque是为了高效实现插入和删除的双向队列。
deque:double-ended queue
class collections.deque([iterable[, maxlen]])
Returns a new deque object initialized left-to-right (using append()) with data from iterable. If iterable is not specified, the new deque is empty.
|
|
这里扩展了很多方便的函数,appendleft(),popleft()等等
defaultdict
可以设置默认值的dict,平时我们使用dict的时候,如果key不存在,会报错
class collections.defaultdict([default_factory[, …]])
Returns a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.
|
|
我们使用defaultdict就可以避免这个错误
这里我们设置默认是int型,默认值为0
Counter
是一个简单的计数器,
class collections.Counter([iterable-or-mapping])
A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.
|
|
这个most_common最好用了感觉,根据次数进行排名
当然,collections中还有很多其他的好用的类,我们可以参考官方文档。