python 遍历 两列表比较A列表中是否存在于B列表的两种方法的 性能测试

在遍历对比中,我曾使用.index函数去对列表元素进行比较,在index函数中,描述为

检测字符串中是否包含子字符串 str

这意味着A元素并不是完全等同于B元素,而是B元素中包含了A元素,在这种情况下,才需要使用到index函数,盲目使用函数或许浪费大部分性能,并且index抛出错误,使用try将再次损耗性能

所以 我做了以下测试,去验证性能

首先使用time模块并定义两个列表用于比较

import time

list=[1,2,3,4,5,6,7]

list1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14]

由于单独运行的结果非常小,所以采用同样的循环增加次数

k=0

while k < 10000:

    k+=1

完整验证代码如下

#列表查找检测
import time
list=[1,2,3,4,5,6,7]
list1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14]

start = time.time()

k=0
while k < 10000:
    k+=1
    for i in list1:
        for n in list:
            if i == n :
                object_listnnnn = i
            else:
                object_listnnnn = i



end = time.time()
print((end - start))
start = time.time()

k=0
while k < 10000:
    k+=1
    for i in list1:
        for n in list:
            try:
                object_listnnnn = list.index(i)
                object_listnnnn = i

            except:
                object_listnnnn = i


end = time.time()
print((end - start))

测试数据如下

1.06718468666077 0.982396841049194 0.918120622634888 0.963332414627075 0.993014097213745 0.984809732437134
0.36103343963623 0.38300609588623 0.279305219650269 0.346380472183228 0.378976345062256 0.349740314483643
2.91480660438538 2.90445351600647 2.81602907180786 2.87438821792603 2.87952947616577 2.8778413772583

明显采用第一种方法速度将是大于一倍

==========修改

在代码段

k=0
while k < 10000:
    k+=1
    for i in list1:
        for n in list:
            try:
                object_listnnnn = list.index(i)
                object_listnnnn = i

            except:
                object_listnnnn = i

中,list.index无需遍历list,将list改为n此遍历才起作用,所以将代码更改如下

tps=0
while tps <5 :
    tps +=1
    #列表查找检测


    import time
    list=[1,2,3,4,5,6,7]
    list1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14]

    start = time.time()

    k=0
    while k < 10000:
        k+=1
        for i in list1:
            for n in list:
                if i == n :
                    object_listnnnn = i
                else:
                    object_listnnnn = i



    end = time.time()
    print((end - start))
    start = time.time()

    k=0
    while k < 10000:
        k+=1
        for i in list1:
            try:
                object_listnnnn = list.index(i)
                object_listnnnn = i
            except:
                object_listnnnn = i



    end = time.time()
    print((end - start))
    start = time.time()



    k=0
    while k < 10000:
        k+=1
        for i in list1:
            for n in list:
                try:
                    object_listnnnn = n.index(i)
                    object_listnnnn = i

                except:
                    object_listnnnn = i

    end = time.time()
    print((end - start))



性能测试如下

平均
0.984809732437134
0.349740314483643
2.8778413772583

你可能感兴趣的:(性能测试,python,python,开发语言,后端)