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

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

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

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

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

改进版:

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

代码:

# 对比某个元素在"列表/元组/字典/集合"的查找速度
# 结论:对于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()
  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值