我是靠谱客的博主 幸福小猫咪,这篇文章主要介绍Python3中`in操作`在列表,字典,集合中的速度对比2(改进版),现在分享给大家,希望可以做个参考。

Python3中in操作在列表,字典,集合中的速度对比2(改进版)

Python3中"in操作(x in X)"在列表list,字典dict,集合set,np.array 中的速度对比2(改进版)

我的原始文章链接:原始文章

上一个 实例(–>click传送门) 的对比不是很明显,主要是用单个元素在一个大空间内查找,太浪费资源了。
在这基础上,思考了一下,为何不用事先定义好的每一个元素就地查找呢。

改进版:

结论:集合和字典查找最快,其次为np.array,最慢的是list和tuple
运行结果:
在这里插入图片描述

代码:

复制代码
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 对比某个元素在"列表/元组/字典/集合"的查找速度 # 结论:对于x in X的操作,集合字典在查找速度上有明显优势 import datetime import numpy as np import matplotlib.pyplot as mp from collections import OrderedDict def f(xx): t0 = datetime.datetime.now() for i in L: if i in xx: continue t1 = datetime.datetime.now() print('-->', type(xx), '遍历结束,耗时%s秒' % ((t1 - t0).total_seconds())) return (t1 - t0).total_seconds() X, y = [], [] n = 5*10**4 L_all = np.arange(0, n) for x in range(0, n+1, 10000): print('nx', x) L = L_all[:x+1] L_result = [] L_result.append(f(L)) L_result.append(f(list(L))) L_result.append(f(tuple(L))) L_result.append(f(set(L))) L_result.append(f(dict(zip(L, [None] * len(L))))) L_result.append(f(OrderedDict(zip(L, [None] * len(L))))) X.append(x) y.append(L_result) mp.title('speed test', fontsize=20) mp.xlabel('Num', fontsize=12) mp.ylabel('Time(s)', fontsize=12) for y, lable, colors in zip( (np.array(y)).T, ['np.array', 'list', 'tuple', 'set', 'dict', 'Orderdict'], ['green', 'red', 'blue', 'orange', 'yellow', 'pink']): mp.plot(X, y, linestyle='-', label=lable, color=colors) mp.scatter(X, y, marker='o', # 点型 ~ matplotlib.markers s=60, # 大小 edgecolor=colors, # 边缘色 facecolor='white', # 填充色 zorder=3 # 绘制图层编号 (编号越大,图层越靠上) ) mp.legend() mp.show()

最后

以上就是幸福小猫咪最近收集整理的关于Python3中`in操作`在列表,字典,集合中的速度对比2(改进版)的全部内容,更多相关Python3中`in操作`在列表,字典,集合中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(98)

评论列表共有 0 条评论

立即
投稿
返回
顶部