• python中in在list和dict中查找效率比较


    转载自:http://blog.csdn.net/wzgbm/article/details/54691615

    首先给一个简单的例子,测测list和dict查找的时间:

    import time  query_lst = [-60000,-6000,-600,-60,-6,0,6,60,600,6000,60000]  lst = [] dic = {}  for i in range(100000000):     lst.append(i)     dic[i] = 1   start = time.time() for v in query_lst:     if v in lst:         continue end1 = time.time()  for v in query_lst:     if v in dic:         continue  end2 = time.time()  print "list search time : %f"%(end1-start) print "dict search time : %f"%(end2-end1) 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    运行结果:

    list search time : 11.836798 
    dict search time : 0.000007

    通过上例我们可以看到list的查找效率远远低于dict的效率,原因如下:

    Python中list对象的存储结构采用的是线性表,因此其查询复杂度为O(n),而dict对象的存储结构采用的是散列表(hash表),其在最优情况下查询复杂度为O(1)。

  • 相关阅读:
    SpringBoot 整合Shiro
    Shiro 学习
    SpringBoot 整合security、thymeleaf
    【SpringBoot__Mybatis】整合MyBatis 配置文件版2
    SpringBoot 配置Druid数据源及监控
    lombok 使用
    thymeleaf 常用
    随机模块
    md5加密
    python正则
  • 原文地址:https://www.cnblogs.com/june0507/p/7601011.html
Copyright © 2020-2023  润新知