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

时间:2018-01-27 22:31:43

标签: python python-2.7 list

是否有最快的方法来获取两个列表的元素并获得具有-21,21之间差异的对

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

我有很多名单,而且它们非常大。

我想把索引作为

[(list1_index1,list2_index1),...]如下所示。

或直接:

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

......等等。

我想在Python 2.7中使用它。

感谢。

3 个答案:

答案 0 :(得分:1)

假设您的范围包含-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)]

此处每对元素与其enumerate()的索引配对,当差值小于或等于21时,返回对的索引。

注意:您可以使用abs(x - y),因为它给出了数字的绝对值。因此,如果我们得到-20的差异,它将返回20.

答案 1 :(得分:1)

我的解决方案,基准测试与@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

答案 2 :(得分:1)

您可以在没有任何外部库的情况下完成:

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))])

输出:

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