Skip to main content
 首页 » 编程设计

python之比较两个大列表以在python中找到满足条件的元素对

2025年05月04日12oomusou

我有两个大的数字列表(每个列表可能有一百万个元素)。我想按元素比较它们,以确定差异小于 0.5 的元素对。我知道两个嵌套的 for 循环不是一个选项。有什么快速的方法可以使用 sets 或 zip 来做到这一点?

例如。如果我的列表是 list1 = [1,2,3,4] 和 list2 = [3,4,5,6] 并且条件差为 1,则该解决方案会将这些对排列在列表中 [list1 中的元素,list2 中的元素,差异]。解决方案是 [[2,3,1],[3,3,0],[3,4,1],[4,3,1],[4,4,0],[4 ,5,1]]

谢谢

请您参考如下方法:

这应该有效。 (批评指正)

基本上,我的想法是对两个列表 O(nlogn) 进行排序,然后遍历列表,在内存中保留与下一个元素的距离,因此,不计算所有对,而只计算一个子集给我a O(2*m*n) m 是允许的最大距离

x = sorted([0, 2, 3, 4]) 
y = sorted([1,3, 4, 5, 6]) 
index = 0 
delta = 1 
output = [] 
j = 0 
value_2 = y[0] 
no_more = False 
number_of_operation = 0 
for i,value_1 in enumerate(x[:]): 
    print(f'Testing for this {value_1}') 
    skip = False 
    try: 
        next_value_at = x[i+1] - value_1  
        if next_value_at > delta: 
            skip = True 
            print('We can directly skip to next') 
    except: 
        print('At the end of list') 
    while value_2 - value_1 <= delta: 
        number_of_operation+=1 
        print(value_1,value_2) 
        try: 
            if abs(value_1 - value_2) <= delta: 
                output += [[value_1,value_2,value_1-value_2]] 
            j+=1 
            value_2 = y[j] 
            print(value_1,value_2)  
            continue 
        except: 
            no_more = True 
            print('end of list') 
            break 
    if not skip: 
        print("Going back") 
        j=index 
        value_2 = y[index] 
    else: 
        index = j 
    if no_more: 
        print('end') 
        break 
    print(number_of_operation)