defaultdict的威力

>>> from collections import defaultdict
>>> s='mmississippi'
>>> d=defaultdict(int)
>>> for i in s:
    d[i]+=1

    
>>> print dict(d)
{'i': 4, 'p': 2, 's': 4, 'm': 2}

 官方文档解释:

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.

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

>>> from collections import defaultdict
>>> def ini(): 
    return 3

>>> d=defaultdict(ini)
>>> d[1]   #可见,不一定要是list,int,float,dict这些工厂函数,自定义函数也能成功.
3
>>> d
defaultdict(<function ini at 0x020CA5F0>, {1: 3})
>>> d[2]
3
>>> d
defaultdict(<function ini at 0x020CA5F0>, {1: 3, 2: 3})
>>> 

再如:

>>> d=defaultdict(ini,{1:2})
>>> d
defaultdict(<function ini at 0x020CA5F0>, {1: 2})
>>> d[3]
3
>>> d
defaultdict(<function ini at 0x020CA5F0>, {1: 2, 3: 3})
>>> d=defaultdict(ini,a=1,b=2)
>>> d
defaultdict(<function ini at 0x020CA5F0>, {'a': 1, 'b': 2})

>>> d=defaultdict(ini,[(1,3)])
>>> d
defaultdict(<function ini at 0x020CA5F0>, {1: 3})

附defaultdict说明文档:

    class defaultdict(__builtin__.dict)
     |  defaultdict(default_factory) --> dict with default factory
     |  
     |  The default factory is called without arguments to produce
     |  a new value when a key is not present, in __getitem__ only.
     |  A defaultdict compares equal to a dict with the same items.
     |  
     |  Method resolution order:
     |      defaultdict
     |      __builtin__.dict
     |      __builtin__.object
     |  
     |  Methods defined here:
     |  
     |  __copy__(...)
     |      D.copy() -> a shallow copy of D.
     |  
     |  __getattribute__(...)
     |      x.__getattribute__('name') <==> x.name
     |  
     |  __init__(...)
     |      x.__init__(...) initializes x; see help(type(x)) for signature
     |  
     |  __missing__(...)
     |      __missing__(key) # Called by __getitem__ for missing key; pseudo-code:
     |      if self.default_factory is None: raise KeyError((key,))
     |      self[key] = value = self.default_factory()
     |      return value
     |  
     |  __reduce__(...)
     |      Return state information for pickling.
     |  
     |  __repr__(...)
     |      x.__repr__() <==> repr(x)
     |  
     |  copy(...)
     |      D.copy() -> a shallow copy of D.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  default_factory
     |      Factory for default value called by __missing__().
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from __builtin__.dict:
     |  
     |  __cmp__(...)
     |      x.__cmp__(y) <==> cmp(x,y)
     |  
     |  __contains__(...)
     |      D.__contains__(k) -> True if D has a key k, else False
     |  
     |  __delitem__(...)
     |      x.__delitem__(y) <==> del x[y]
     |  
     |  __eq__(...)
     |      x.__eq__(y) <==> x==y
     |  
     |  __ge__(...)
     |      x.__ge__(y) <==> x>=y
     |  
     |  __getitem__(...)
     |      x.__getitem__(y) <==> x[y]
     |  
     |  __gt__(...)
     |      x.__gt__(y) <==> x>y
     |  
     |  __iter__(...)
     |      x.__iter__() <==> iter(x)
     |  
     |  __le__(...)
     |      x.__le__(y) <==> x<=y
     |  
     |  __len__(...)
     |      x.__len__() <==> len(x)
     |  
     |  __lt__(...)
     |      x.__lt__(y) <==> x<y
     |  
     |  __ne__(...)
     |      x.__ne__(y) <==> x!=y
     |  
     |  __setitem__(...)
     |      x.__setitem__(i, y) <==> x[i]=y
     |  
     |  __sizeof__(...)
     |      D.__sizeof__() -> size of D in memory, in bytes
     |  
     |  clear(...)
     |      D.clear() -> None.  Remove all items from D.
     |  
     |  fromkeys(...)
     |      dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
     |      v defaults to None.
     |  
     |  get(...)
     |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
     |  
     |  has_key(...)
     |      D.has_key(k) -> True if D has a key k, else False
     |  
     |  items(...)
     |      D.items() -> list of D's (key, value) pairs, as 2-tuples
     |  
     |  iteritems(...)
     |      D.iteritems() -> an iterator over the (key, value) items of D
     |  
     |  iterkeys(...)
     |      D.iterkeys() -> an iterator over the keys of D
     |  
     |  itervalues(...)
     |      D.itervalues() -> an iterator over the values of D
     |  
     |  keys(...)
     |      D.keys() -> list of D's keys
     |  
     |  pop(...)
     |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
     |      If key is not found, d is returned if given, otherwise KeyError is raised
     |  
     |  popitem(...)
     |      D.popitem() -> (k, v), remove and return some (key, value) pair as a
     |      2-tuple; but raise KeyError if D is empty.
     |  
     |  setdefault(...)
     |      D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
     |  
     |  update(...)
     |      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
     |      If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
     |      If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
     |      In either case, this is followed by: for k in F: D[k] = F[k]
     |  
     |  values(...)
     |      D.values() -> list of D's values
     |  
     |  viewitems(...)
     |      D.viewitems() -> a set-like object providing a view on D's items
     |  
     |  viewkeys(...)
     |      D.viewkeys() -> a set-like object providing a view on D's keys
     |  
     |  viewvalues(...)
     |      D.viewvalues() -> an object providing a view on D's values
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from __builtin__.dict:
     |  
     |  __hash__ = None
     |  
     |  __new__ = <built-in method __new__ of type object>
     |      T.__new__(S, ...) -> a new object with type S, a subtype of T
原文地址:https://www.cnblogs.com/xiangnan/p/3395581.html