基于特定距离(阈值)的两个列表的交集

时间:2018-06-24 18:57:09

标签: python performance intersection

我想从list1中找到与list2中的值足够接近的值(基于指定的阈值),即与以下代码相似的功能。 但是,与pyhton的intersect_with_threshold()交集相比,下面的set的实现非常慢(慢许多个数量级!) 不幸的是,python的set交集对我的目的没有帮助,因为我需要使用阈值来选择相交的值。 谁能指导我如何加快intersect_with_threshold()功能? 提前谢谢

import time
import random

ln=100
list1=[]
list2=[]
#generating the two lists
for i in range(1000):
    list1.append(round(random.random()*ln))
    list2.append(round(random.random()*ln))

# custom intersection function with a threshold    
def intersect_with_theshold(lst1, lst2, threshold):
    intersected_list=[]
    for j in lst1:
        for i in lst2:
            d = abs(i - j)
            if(d < threshold):
                intersected_list.append(j)
    return list(set(intersected_list))  

## using the custom made intersection function    
t1=time.time()
out1=intersect_with_theshold(list1, list2, 0.001)
t2=time.time()
print(t2-t1)    

## using inbuilt python intersection function 
t1=time.time()
out2=(list(set(list1).intersection(list2)))
t2=time.time()
print(t2-t1)

1 个答案:

答案 0 :(得分:1)

尝试避免将一个列表中的每个项目与另一列表中的每个项目进行比较。

在这种情况下,它有助于对列表进行排序。我希望从代码中可以清楚地知道这个想法。一个或另一个索引递增。 (与您一样,使用ilst2编制索引,为j编制索引lst1。)

def intersect_with_theshold(lst1, lst2, threshold):
    intersected_list=[]
    lst2 = sorted(lst2)
    i = 0
    for j in sorted(lst1):
        lower = j - threshold
        try:
            while not lower < lst2[i]:
                i += 1
        except IndexError:
            break
        if lst2[i] < j + threshold:
            intersected_list.append(j)
    return list(set(intersected_list))