python测试list,set,dict查询速度
测试代码
import datetime
num = 100000
data_list = list(range(num))
def dict_test(data_list):
data_dict = {i: i for i in data_list}
for i in range(num):
if data_dict.get(i):
continue
def list_test(data_list):
for i in range(num):
if i in data_list:
continue
def set_test(data_list):
data_set = set(data_list)
for i in range(num):
if i in data_set:
continue
if __name__ == '__main__':
time1 = datetime.datetime.now()
print('开始时间:%s' % time1)
list_test(data_list)
time2 = datetime.datetime.now()
print('list结束时间:%s' % time2)
print('list用时:%s' % (time2 - time1))
set_test(data_list)
time3 = datetime.datetime.now()
print('set结束时间:%s' % time3)
print('set用时:%s' % (time3 - time2))
dict_test(data_list)
time4 = datetime.datetime.now()
print('dict结束时间:%s' % time4)
print('dict用时:%s' % (time4 - time3))
print('结束')
测试结果
Press ENTER or type command to continue
开始时间:2020-11-11 08:51:19.893328
list结束时间:2020-11-11 08:52:35.087357
list用时:0:01:15.194029
set结束时间:2020-11-11 08:52:35.104850
set用时:0:00:00.017493
dict结束时间:2020-11-11 08:52:35.161417
dict用时:0:00:00.056567
结束
结论
查找速度: set > dict >> list
所以如果使用python判断某个值是否存在于一个大列表中时,需要先把列表转成集合