from random import randrange from timeit import * import sys l = [randrange(1000) for i in range(100)] print(sys.getsizeof(l)) s = set(l) print(sys.getsizeof(s)) def checklisttime(): for i in range(0, 5000000): if i in l: pass def checksettime(): for i in range(0, 5000000): if i in s: pass listtime = timeit("checklisttime()", "from __main__ import checklisttime", number=1) settime = timeit("checksettime()", "from __main__ import checksettime", number=1) print(listtime) print(settime)
从结果来看:set查找由于list查找,但是set消耗的内存空间大于list的数据的内存空间。
Set用的是bst 查找操作时间复杂度logn
List是线性表 查找时间复杂度n
运行结果如下:
912
84168.554053954
0.4606272709999999