美文网首页
高阶字典

高阶字典

作者: Modelstrategy | 来源:发表于2017-12-19 00:34 被阅读0次
    # setfault()处理字典缺失的键
    d = {'hydrogen':1, 'helium':2}
    
    try:
        a = d['carbon']
    
    except KeyError:
        print('key not exist')
    
    b = d.setdefault('carbon', 12)
    print('after setfault: \n', d)
    
    # setfault()不会改变已存在的键值对
    c =d.setdefault('helium', 1234)
    print('will it change?\n', d, '\n of course not!')
    
    # 用defaultdict()处理字典缺失的键
    
    from collections import defaultdict
    
    # defaultdict() 的参数为一个函数
    d = defaultdict(int)
    print(d['C4TMAN'])
    
    
    def hehe():
        return '大概是个傻子吧'
    
    
    d = defaultdict(hehe)
    print(d['C4TMAN'])
    
    # 使用int定义计数器
    # 若指代defaultdict的变量为非字典,将返回一个空子典
    
    dict_counter = defaultdict(int)
    L = ['sb', 'sb', 'sb', 'hehe', 'hehe']
    
    for ele in L:
        dict_counter[ele] += 1
    
    for key, value in dict_counter.items():
        print('there are ', value, key + 's')
    
    # Counter() 接受一个列表,并返回一个以元素及其数量为键值对的字典( 其实是一个Counter的对象 )
    from collections import Counter
    
    for key, value in Counter(L).items():
        print('there are ', value, key + 's')
    
    # most_common方法以降序返回元素
    L_counter = Counter(L)
    print(L_counter.most_common())
    
    # most_common 接受一个整数做参数,并返回那个参数前的所有元素
    print(L_counter.most_common(1))
    
    L2 = ['hehe', 'hehe', 'hehe', 'C4TMAN', 'C4TMAN', 'WJY']
    L2_counter = Counter(L2)
    
    # Counter之间的运算
    print(L_counter + L2_counter)  # Counter({'hehe': 5, 'sb': 3, 'C4TMAN': 2, 'WJY': 1})
    print(L2_counter - L_counter)  # Counter({'C4TMAN': 2, 'hehe': 1, 'WJY': 1})
    print(L2_counter & L_counter)  # Counter({'hehe': 2})
    print(L2_counter | L_counter)  # Counter({'hehe': 3, 'sb': 3, 'C4TMAN': 2, 'WJY': 1})
                                   # 对于共有项,计数不会相加,而是取最大值
    

    相关文章

      网友评论

          本文标题:高阶字典

          本文链接:https://www.haomeiwen.com/subject/ojwvwxtx.html