python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python list、dict、set查询速度

python中list、dict、set查询速度详细对比

作者:needones

在Python编程语言中list、set和dict是三种常用的数据结构,它们各自有着不同的用途和特性,这篇文章主要介绍了python中list、dict、set查询速度详细对比的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

前言

平常使用的时候,可能对于这三种类型的查询无感,因为数据量小的时候查询速度都很快,所以无感觉,今天来试试。

一百万数据测试

=b list=
0.013915400000000133
=c dict=
2.100000000115898e-06
=d set=
9.999999996956888e-07

一千万数据测试

=b list=
0.12139450000000096
=c dict=
2.9000000001389026e-06
=d set=
1.1000000004202093e-06

一亿数据测试

=b list=
14.738766999999996
=c dict=
0.0010382000000106473
=d set=
0.0005590999999753876

测试代码

b = []
c = {}
d = set()

for i in range(1000000):  # 此处调整数据量
    num = random.randint(0, 10000000000)

    b.append(num)
    c[num] = 1
    d.add(num)

print('=========b list=========')
time1 = time.perf_counter()
if 9999 in b:
    print("yes")
time2 = time.perf_counter()
print(time2 - time1)
print('=========c dict=========')
time1 = time.perf_counter()
if 9999 in c:
    print("yes")
time2 = time.perf_counter()
print(time2 - time1)
print('=========d set=========')
time1 = time.perf_counter()
if 9999 in d:
    print("yes")
time2 = time.perf_counter()
print(time2 - time1)

结论

从上面数据来看,set > dict >> list

list查询速度最慢,性能上差距上万倍

字典: dict会把所有的key变成hash 表,然后将这个表进行排序,这样,你通过data[key]去查data字典中一个key的时候,python会先把这个key hash成一个数字,然后拿这个数字到hash表中看没有这个数字, 如果有,拿到这个key在hash表中的索引,拿到这个索引去与此key对应的value的内存地址那取值就可以了。

集合: 集合的存储方式和字典key类似,都是采用hash存储,相同的值对应相同的地址,所以set中没有相同值,也是无序的

冷知识:你知道这两个有什么区别吗,哪个更快?

a = list()
b = []

有兴趣的小伙伴尝试一下

t1 = time.perf_counter()
a = list()
t2 = time.perf_counter()
print(f"a = list() cost :{t2 - t1}")

t1 = time.perf_counter()
b = []
t2 = time.perf_counter()
print(f"b = []     cost :{t2 - t1}")

总结 

到此这篇关于python中list、dict、set查询速度详细对比的文章就介绍到这了,更多相关python list、dict、set查询速度内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文