字典key默认值的设置方法及其测试结果

三种方法, 在生成字典的过程中,对字典的key的默认值进行设置,
消耗时间的长短测试

方法以及代码

#coding: utf8

"""
三种方法, 在生成字典的过程中,对字典的key的默认值进行设置
花费时间的长短测试
"""
import time

def testDict(string_times):
    s = "hello" * string_times
    print( "string len is {0}".format(len(s)))

    # 方法1
    d1 = dict()
    t1 = time.time()
    for ch in s:
        d1.setdefault(ch, 0)
        d1[ch] += 1
    t2 = time.time()
    print("d1 = ", t2 - t1)

    # 方法2
    d2 = dict()
    for ch in s:
        d2[ch] = d2.get(ch, 0) + 1
    t3 = time.time()
    print("d2 = ", t3 - t2)

    # 方法3
    import collections
    d3 = collections.defaultdict(int)
    for ch in s:
        d3[ch] += 1
    t4 = time.time()
    print("d3 = ", t4 - t3)


    if d1 == d2 and d1 == d3 and d2 == d3:
        print "dictionary value equal ", d1 == d2, d1 == d3, d2 == d3
    else:
        print "error"
    print("-" * 30)

def main():
    testDict(100)
    testDict(1000)
    testDict(10000)
    testDict(100000)

if __name__ == "__main__":
    main()

生成结果

结论在生成字典的过程中:
对于遍历较大的序列,collections.defaultdict(int) 的方法, 在效率上有较为明显的优势。
对于遍历较小的序列,字典的get和setdefault方法效率上接近,且两个方法优collections.defaultdict(int)

“`
string len is 500
(‘d1 = ‘, 0.0)
(‘d2 = ‘, 0.0)
(‘d3 = ‘, 0.005000114440917969)

dictionary value equal True True True

string len is 5000
(‘d1 = ‘, 0.0009999275207519531)
(‘d2 = ‘, 0.0009999275207519531)
(‘d3 = ‘, 0.0010001659393310547)

dictionary value equal True True True

string len is 50000
(‘d1 = ‘, 0.013000011444091797)
(‘d2 = ‘, 0.011999845504760742)
(‘d3 = ‘, 0.006000041961669922)

dictionary value equal True True True

string len is 500000
(‘d1 = ‘, 0.127000093460083)
(‘d2 = ‘, 0.11800003051757812)
(‘d3 = ‘, 0.06399989128112793)
dictionary value equal True True True
——————————“`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值