当前位置: 代码网 > it编程>前端脚本>Python > python中list、dict、set查询速度详细对比

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

2026年03月10日 Python 我要评论
前言平常使用的时候,可能对于这三种类型的查询无感,因为数据量小的时候查询速度都很快,所以无感觉,今天来试试。一百万数据测试=b list=0.013915400000000133=c dict=2.1

前言

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

一百万数据测试

=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查询速度内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com