简体   繁体   English

查找具有范围的两个列表的元素对

[英]find the pairs of elements of two lists with a range

Is there a fastest way to get elements of the two lists and get the pairs that have difference between -21,21 是否有最快的方法来获取两个列表中的元素并获取-21,21之间有差异的对

list1 = [0,10,20]
list2 = [0,10,20,30,40,50]

I have really many lists and they are really large. 我的名单很多,而且很大。

what I want to get the indexes as 我想要得到的索引

[(list1_index1,list2_index1), ...] as below. [(list1_index1,list2_index1),...]如下。

or directly: 或直接:

diff: 0, lists1_index = 0, lists2_index = 0
diff: -10, lists1_index = 0, lists2_index = 1
diff: -20, lists1_index = 0, lists2_index = 2
diff: 10, lists1_index = 1, lists2_index = 0
diff: 0, lists1_index = 1, lists2_index = 1
diff: -10, lists1_index = 1, lists2_index = 2
diff: -20, lists1_index = 1, lists2_index = 3

... and so on. ... 等等。

I want to that in Python 2.7. 我想在Python 2.7中做到这一点。

thanks. 谢谢。

Assuming your range is inclusive of -21 and 21, what about using itertools.product() with a list comprehension: 假设您的范围包括-21和21,那么如何将itertools.product()与列表理解一起使用:

>>> from itertools import product
>>> list1 = [0,10,20]
>>> list2 = [0,10,20,30,40,50]
>>> [(i1, i2) for (i1, x1), (i2, x2) in product(enumerate(list1), enumerate(list2)) if abs(x1 - x2) <= 21]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]

Here each pair of elements is paired with their indices with enumerate() , and when the difference is less than or equal to 21, the indices of the pairs are returned. 在这里,每对元素与它们的索引与enumerate()配对,并且当差值小于或等于21时,将返回该对元素的索引。

Note: You can use abs(x - y) , since it gives the absolute value of a number. 注意:可以使用abs(x - y) ,因为它给出了数字的绝对值。 So if we get a difference of -20, it will give back 20. 因此,如果我们得到-20的差,它将返还20。

My solution below, with benchmarking versus @RoadRunner. 我下面的解决方案,使用基准测试与@RoadRunner进行比较。

from numba import jit

lst1 = np.random.randint(0, 10, 1000)
lst2 = np.random.randint(0, 10, 1000)

# jp_data_analysis
@jit(nopython=True)
def differencer(l1, l2, n):
    return [(x_i, y_i) for x_i, x in enumerate(lst1) for (y_i, y) in enumerate(lst2) if abs(x-y) <= n]            

# RoadRunner
def differencer2(l1, l2, n):
    return [(i1, i2) for (i1, x1), (i2, x2) in product(enumerate(l1), enumerate(l2)) if abs(x1 - x2) <= n]

assert set(differencer(lst1, lst2, 21)) == set(differencer2(lst1, lst2, 21))

%timeit differencer(lst1, lst2, 21)     # 411ms
%timeit differencer2(lst1, lst2, 21)    # 1.02s

You can simply do without any external library: 您可以简单地在没有任何外部库的情况下进行操作:

list1 = [0,10,20]
list2 = [0,10,20,30,40,50]

print([(j,k) for j,i in enumerate(list1) for k,l in enumerate(list2) if (i-l) in list(range(-21,22))])

output: 输出:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM