美文网首页
Python中defaultdict用法

Python中defaultdict用法

作者: 致Great | 来源:发表于2018-06-08 12:43 被阅读32次
    • defaultdict类就好像是一个dict,但是它是使用一个类型来初始化的
    • defaultdict类的初始化函数接受一个类型作为参数,当所访问的键不存在的时候,可以实例化一个值作为默认值
    • defaultdict类除了接受类型名称作为初始化函数的参数之外,还可以使用任何不带参数的可调用函数,到时该函数的返回结果作为默认值,这样使得默认值的取值更加灵活。
    strings = ('puppy', 'kitten', 'puppy', 'puppy',
               'weasel', 'puppy', 'kitten', 'puppy')
    counts = {}
    """
        单词统计
    """
    # 方法1 使用判断语句检查
    for word in strings:
        if word not in counts:
            counts[word] = 1
        else:
            counts[word] += 1
    print(counts)
    
    # 方法2 使用dict.setdefault()方法来设置默认值:
    counts = {}
    for word in strings:
        counts.setdefault(word, 0)
        counts[word] += 1
    print(counts)
    
    # 方法3 使用collections.defaultdict
    from collections import defaultdict
    counts = defaultdict(lambda: 0)
    for word in strings:
        counts[word] += 1
    print(counts)
    

    结果:

    {'puppy': 5, 'kitten': 2, 'weasel': 1}
    {'puppy': 5, 'kitten': 2, 'weasel': 1}
    defaultdict(<function <lambda> at 0x0000000001D12EA0>, {'puppy': 5, 'kitten': 2, 'weasel': 1})
    [Finished in 0.1s]
    

    更多:
    https://www.cnblogs.com/jidongdeatao/p/6930325.html

    相关文章

      网友评论

          本文标题:Python中defaultdict用法

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