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)。

posted @ 2017-09-27 11:51  算法技术前沿  阅读(2497)  评论(0编辑  收藏  举报