zoukankan      html  css  js  c++  java
  • Python collections系列之默认字典

    默认字典(defaultdict) 

    defaultdict是对字典的类型的补充,它默认给字典的值设置了一个类型。

    1、创建默认字典

    import collections
    
    dic = collections.defaultdict(list)    # 设置dic的值类型为list
    dic['k1'].append('evescn')

    2、查看默认字典

    print(dic)
    
    输出结果:
    defaultdict(<class 'list'>, {'k1': ['evescn']})

    3、查看默认字典的方法

    >>> dir(dic)
    ['__class__', '__contains__', '__copy__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__missing__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'default_factory', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
    class defaultdict(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.
        All remaining arguments are treated the same as if they were
        passed to the dict constructor, including keyword arguments.
        """
        def copy(self): # real signature unknown; restored from __doc__
            """ D.copy() -> a shallow copy of D. """
            pass
    
        def __copy__(self, *args, **kwargs): # real signature unknown
            """ D.copy() -> a shallow copy of D. """
            pass
    
        def __getattribute__(self, name): # real signature unknown; restored from __doc__
            """ x.__getattribute__('name') <==> x.name """
            pass
    
        def __init__(self, default_factory=None, **kwargs): # known case of _collections.defaultdict.__init__
            """
            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.
            All remaining arguments are treated the same as if they were
            passed to the dict constructor, including keyword arguments.
            
            # (copied from class doc)
            """
            pass
    
        def __missing__(self, key): # real signature unknown; restored from __doc__
            """
            __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
            """
            pass
    
        def __reduce__(self, *args, **kwargs): # real signature unknown
            """ Return state information for pickling. """
            pass
    
        def __repr__(self): # real signature unknown; restored from __doc__
            """ x.__repr__() <==> repr(x) """
            pass
    
        default_factory = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """Factory for default value called by __missing__()."""
    defaultdict

    4、练习

    有如下值集合 [11,22,33,44,55,66,77,88,99,90...],
    将所有大于 66 的值保存至字典的第一个key中,
    将小于 66 的值保存至第二个key的值中。
    即: {'k1': 大于66 , 'k2': 小于66}
    
    # 原生字典
    values = [11, 22, 33,44,55,66,77,88,99,90] my_dict = {} for value in values: if value>66: if my_dict.has_key('k1'): my_dict['k1'].append(value) else: my_dict['k1'] = [value] else: if my_dict.has_key('k2'): my_dict['k2'].append(value) else: my_dict['k2'] = [value]
    # 默认字典
    
    from collections import defaultdict
    
    values = [11, 22, 33,44,55,66,77,88,99,90]
    
    my_dict = defaultdict(list)
    
    for value in  values:
        if value>66:
            my_dict['k1'].append(value)
        else:
            my_dict['k2'].append(value)
    
    defaultdict字典解决方法
  • 相关阅读:
    Tinyhttpd
    Fiddler教程(Web调试工具)
    windows消息值全部定义,从消息值得到消息名称(系统消息定义从0到1023,从1024开始就是WM_USER,但是中间有325个WM_undefined消息,估计是备用,另外各控件都有一些reserved消息,也是为了备用)LostSpeed
    生意经:凡是现今比较会赚钱或是规模比较大的软件公司大都属于开发"消费型软件"的公司(而且登广告,应该定低价进行销售)
    Folly: Facebook Open-source Library Readme.md 和 Overview.md(感觉包含的东西并不多,还是Boost更有用)
    DefaultFilesMiddleware中间件如何显示默认页面
    Linux模块编程框架
    编程一小时
    DirectoryBrowserMiddleware中间件如何呈现目录结构
    gRpc NET Core
  • 原文地址:https://www.cnblogs.com/evescn/p/7511403.html
Copyright © 2011-2022 走看看