Python基础(4)- collections

昨天用到了这个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的时候,像这样

point_a = 1,3

point_b = 2,6

point_a
Out[37]: (1, 3)

point_b
Out[38]: (2, 6)

point_a[0]
Out[39]: 1

point_a[1]
Out[40]: 3

我们是那个namedtuple就可以这样了

from collections import namedtuple

Point = namedtuple('Point',['x','y'])

point_a = Point(2,2)

point_b = Point(3,3)

point_a
Out[45]: Point(x=2, y=2)

point_b
Out[46]: Point(x=3, y=3)

point_a.x
Out[47]: 2

point_b.y
Out[48]: 3

这样使用一个坐标位置,是不是可读性更强呢,而且用起来也很方便
我们可以看看这个Point是怎样定义的

print(point_a._source)
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict

class Point(tuple):
    'Point(x, y)'

    __slots__ = ()

    _fields = ('x', 'y')

    def __new__(_cls, x, y):
        'Create new instance of Point(x, y)'
        return _tuple.__new__(_cls, (x, y))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Point object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def _replace(_self, **kwds):
        'Return a new Point object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('x', 'y'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % list(kwds))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return self.__class__.__name__ + '(x=%r, y=%r)' % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values.'
        return OrderedDict(zip(self._fields, self))

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

    x = _property(_itemgetter(0), doc='Alias for field number 0')

    y = _property(_itemgetter(1), doc='Alias for field number 1')

下面还有个更好用的地方,我们再读取CSV或者数据库的时候,会返回结果集,这个时候用起来更方便,比如:

import csv
from collections import namedtuple
       
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
for emp in map(EmployeeRecord._make, csv.reader(open(r'D:\document\python_demo\employee_data.csv'))):
    print(emp.name, emp.title)
    print('emp:',emp)


runfile('D:/document/python_demo/demo_hi.py', wdir='D:/document/python_demo')
lufei leader
emp: EmployeeRecord(name='lufei', age='20', title='leader', department='onepiece', paygrade='100')
namei teacher
emp: EmployeeRecord(name='namei', age='19', title='teacher', department='onepiece', paygrade='999')

_make

somenamedtuple._make(iterable)
Class method that makes a new instance from an existing sequence or iterable.

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.

from collections import deque

a = deque(list('abcdef'))

a
Out[80]: deque(['a', 'b', 'c', 'd', 'e', 'f'])

a.append('x')

a.append('y')

a
Out[83]: deque(['a', 'b', 'c', 'd', 'e', 'f', 'x', 'y'])

a.appendleft('w')

a
Out[85]: deque(['w', 'a', 'b', 'c', 'd', 'e', 'f', 'x', 'y'])

a.pop()
Out[86]: 'y'

a.popleft()
Out[87]: 'w'

这里扩展了很多方便的函数,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.

a = {'name':'lufe','age':20}

a
Out[105]: {'age': 20, 'name': 'lufe'}

a['name']
Out[106]: 'lufe'

a['age']
Out[107]: 20

a['score']
Traceback (most recent call last):

  File "<ipython-input-108-99f54e089332>", line 1, in <module>
    a['score']

KeyError: 'score'

我们使用defaultdict就可以避免这个错误

from collections import defaultdict

b = defaultdict(int)

b['name']='lufei'

b
Out[123]: defaultdict(int, {'name': 'lufei'})

b['age']
Out[124]: 0

这里我们设置默认是int型,默认值为0

x = defaultdict(0)
Traceback (most recent call last):

  File "<ipython-input-125-dd2052e23af0>", line 1, in <module>
    x = defaultdict(0)

TypeError: first argument must be callable or None


x = defaultdict(lambda : 100)

x
Out[127]: defaultdict(<function __main__.<lambda>>, {})

x['name']
Out[128]: 100

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.

from collections import Counter

cnt = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])

cnt
Out[131]: Counter({'blue': 3, 'green': 1, 'red': 2})

cnt.most_common(1)
Out[132]: [('blue', 3)]

cnt.most_common(-1)
Out[133]: []

cnt.elements
Out[134]: <bound method Counter.elements of Counter({'blue': 3, 'red': 2, 'green': 1})>

cnt.most_common(3)[:-2:-1]
Out[137]: [('green', 1)]

这个most_common最好用了感觉,根据次数进行排名

当然,collections中还有很多其他的好用的类,我们可以参考官方文档。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,783评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,396评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,834评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,036评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,035评论 5 362
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,242评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,727评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,376评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,508评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,415评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,463评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,140评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,734评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,809评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,028评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,521评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,119评论 2 341

推荐阅读更多精彩内容