zoukankan      html  css  js  c++  java
  • defaultdict使用及__missing__理解

    import collections
    import re
    
    WORD_RE = re.compile(r'w+')
    
    index = collections.defaultdict(list) #用list方法作为默认工厂创建一个默认字典
    with open('xx.txt',encoding='utf-8') as fp:
        for line_no,line in enumerate(fp,1):
            for match in WORD_RE.findeiter(line):
                word = match.group()
                column_no = match.start()+1
                location = (line_no,column_no)
                index[word].append(location) # 如果index没有Word记录,会调用默认工厂,创建一个空列表
    
    for word in sorted(index,key=str.upper):
        print(word,index[word])
    import collections
    
    class StrKeyDict(collections.UserDict):
        def __missing__(self,key):
            if isinstance(key,str):
                raise KeyError(key)
            return self[str(key)]
        def __contains__(self,key):
            return str(key) in self.data
    
        def __setitem__(self,key,item):
            self.data[str(key)] = item

     不可变映射类型

    import collections
    from types import MappingProxyType
    
    d = {1:'A'}
    d_proxy = MappingProxyType(d)
    d_proxy[1] # A
    d_proxy[2] #报错因为不可变
    d_proxy[2] = 'B' #{1:'A',2:'B'}
  • 相关阅读:
    自然常数e怎么得来的?
    一元线性回归模型
    最小二乘法
    Box-Cox转换
    需要的数学技能
    偏导数
    FineReport 表格分类
    FineReport 普通报表
    FineReport 单元格
    FineReport创建普通报表的流程
  • 原文地址:https://www.cnblogs.com/Erick-L/p/8288537.html
Copyright © 2011-2022 走看看