colletions

语法

im_self 是一个实例方法所属的对象
im_func 是这个方法对应的函数对象

defaultdict

是有默认工厂函数的字典。

missing

getitem没有获取到值后(注意,只有getitem方法是,而get方法则不会触发),调用该方法
默认的实现为:

self[key] = value = self.default_factory()

例子

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)

for k, v in s:
    d[k].append(v)

d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

deque

counter

是用于给可hash对象进行计数的dict,可以为负值的。

class collections.Counter([iterable-or-mapping])

elements()

按照每个object的数量返回一个列表,如果数量小于1的就不显示

c = Counter(a=4, b=2, c=0, d=-2)
list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']

most_common([n])

返回最多的n个,如果没指定n或传递了None,则为所有的。

Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

subtract([iterable-or-maping])

减去传递的参数中的值的数量,可以传递list map 或者counter

c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

namedtuple

orderdict

class OrderedDict(dict):

    def __init__(*args, **kwds):

        if not args:
            raise TypeError("descriptor '__init__' of 'OrderedDict' object "
                            "needs an argument")
        self = args[0]
        args = args[1:]
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        try:
            self.__root
        except AttributeError:
            self.__root = root = []                     # sentinel node
            root[:] = [root, root, None]
            self.__map = {}
        self.__update(*args, **kwds)

    def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
      
        if key not in self:
            root = self.__root
            last = root[0]
            last[1] = root[0] = self.__map[key] = [last, root, key]
        return dict_setitem(self, key, value)

    def __delitem__(self, key, dict_delitem=dict.__delitem__):
        'od.__delitem__(y) <==> del od[y]'
       
        dict_delitem(self, key)
        link_prev, link_next, _ = self.__map.pop(key)
        link_prev[1] = link_next                        # update link_prev[NEXT]
        link_next[0] = link_prev                        # update link_next[PREV]

    def __iter__(self):
     
        root = self.__root
        curr = root[1]                                  # start at the first node
        while curr is not root:
            yield curr[2]                               # yield the curr[KEY]
            curr = curr[1]                              # move to next node

    def __reversed__(self):
       
        root = self.__root
        curr = root[0]                                  # start at the last node
        while curr is not root:
            yield curr[2]                               # yield the curr[KEY]
            curr = curr[0]                              # move to previous node

    def clear(self):

        root = self.__root
        root[:] = [root, root, None]
        self.__map.clear()
        dict.clear(self)


    def keys(self):
        return list(self)
    def values(self):
        return [self[key] for key in self]
    def items(self):
        return [(key, self[key]) for key in self]
    def iterkeys(self):
        return iter(self)
    def itervalues(self):
        for k in self:
            yield self[k]
    def iteritems(self):
        for k in self:
            yield (k, self[k])

    update = MutableMapping.update

    __update = update # let subclasses override update without breaking __init__

    __marker = object()

    def pop(self, key, default=__marker):
       
        if key in self:
            result = self[key]
            del self[key]
            return result
        if default is self.__marker:
            raise KeyError(key)
        return default

    def setdefault(self, key, default=None):
        if key in self:
            return self[key]
        self[key] = default
        return default

    def popitem(self, last=True):

        if not self:
            raise KeyError('dictionary is empty')
        key = next(reversed(self) if last else iter(self))
        value = self.pop(key)
        return key, value

    def copy(self):
        return self.__class__(self)

    @classmethod
    def fromkeys(cls, iterable, value=None):
      
        self = cls()
        for key in iterable:
            self[key] = value
        return self

    def __eq__(self, other):
        
        if isinstance(other, OrderedDict):
            return dict.__eq__(self, other) and all(_imap(_eq, self, other))
        return dict.__eq__(self, other)

    def __ne__(self, other):
        return not self == other

    def viewkeys(self):
        return KeysView(self)
    def viewvalues(self):
        return ValuesView(self)
    def viewitems(self):
        return ItemsView(self)

你可能感兴趣的:(colletions)