如何有效地找到两个列表

时间:2018-03-13 02:44:55

标签: python algorithm matching

我正在处理两个大型数据集,我的问题如下。

假设我有两个列表:

list1 = [A,B,C,D]

list2 = [B,D,A,G]

除了O(n 2 )搜索之外,如何使用Python有效地找到匹配的索引?结果应如下所示:

matching_index(list1,list2) -> [(0,2),(1,0),(3,1)]

5 个答案:

答案 0 :(得分:11)

没有重复

如果您的对象是可清除的并且您的列表没有重复项,则可以创建第一个列表的反向索引,然后遍历第二个列表。这只会遍历每个列表一次,因此是O(n)

def find_matching_index(list1, list2):

    inverse_index = { element: index for index, element in enumerate(list1) }

    return [(index, inverse_index[element])
        for index, element in enumerate(list2) if element in inverse_index]

find_matching_index([1,2,3], [3,2,1]) # [(0, 2), (1, 1), (2, 0)]

带有重复项

您可以将之前的解决方案扩展到重复帐户。您可以使用set跟踪多个索引。

def find_matching_index(list1, list2):

    # Create an inverse index which keys are now sets
    inverse_index = {}

    for index, element in enumerate(list1):

        if element not in inverse_index:
            inverse_index[element] = {index}

        else:
            inverse_index[element].add(index)

    # Traverse the second list    
    matching_index = []

    for index, element in enumerate(list2):

        # We have to create one pair by element in the set of the inverse index
        if element in inverse_index:
            matching_index.extend([(x, index) for x in inverse_index[element]])

    return matching_index

find_matching_index([1, 1, 2], [2, 2, 1]) # [(2, 0), (2, 1), (0, 2), (1, 2)]

不幸的是,这不再是 O(n)。考虑输入[1, 1][1, 1]的情况,输出为[(0, 0), (0, 1), (1, 0), (1, 1)]。因此,根据输出的大小,最坏的情况不能比O(n^2)好。

虽然如果没有重复项,此解决方案仍为O(n)

不可售的物品

现在出现的情况是您的对象不可清洗,但具有可比性。这里的想法是以保留每个元素的原始索引的方式对列表进行排序。然后我们可以对等于获得匹配索引的元素序列进行分组。

由于我们在以下代码中大量使用groupbyproduct,因此我使find_matching_index返回一个生成器,以便在长列表中提高内存效率。

from itertools import groupby, product

def find_matching_index(list1, list2):
    sorted_list1 = sorted((element, index) for index, element in enumerate(list1))
    sorted_list2 = sorted((element, index) for index, element in enumerate(list2))

    list1_groups = groupby(sorted_list1, key=lambda pair: pair[0])
    list2_groups = groupby(sorted_list2, key=lambda pair: pair[0])

    for element1, group1 in list1_groups:
        try:
            element2, group2 = next(list2_groups)
            while element1 > element2:
                (element2, _), group2 = next(list2_groups)

        except StopIteration:
            break

        if element2 > element1:
            continue

        indices_product = product((i for _, i in group1), (i for _, i in group2), repeat=1)

        yield from indices_product

        # In version prior to 3.3, the above line must be
        # for x in indices_product:
        #     yield x

list1 = [[], [1, 2], []]
list2 = [[1, 2], []]

list(find_matching_index(list1, list2)) # [(0, 1), (2, 1), (1, 0)]

事实证明,时间复杂度并没有那么大。排序当然需要O(n log(n)),但是groupby提供的生成器可以通过仅遍历我们的列表两次来恢复所有元素。结论是我们的复杂性主要受product输出大小的约束。因此,给出最佳情况,其中算法为O(n log(n)),最坏情况为O(n^2)

答案 1 :(得分:4)

如果您的对象不可缓存但仍可订购,您可能需要考虑使用sorted来匹配两个列表

假设两个列表中的所有元素都匹配

您可以对列表索引进行排序并将结果配对

indexes1 = sorted(range(len(list1)), key=lambda x: list1[x])
indexes2 = sorted(range(len(list2)), key=lambda x: list2[x])
matches = zip(indexes1, indexes2)

如果并非所有元素都匹配,但每个列表中没有重复项

您可以同时对两者进行排序,并在排序时保留索引。然后,如果您捕获任何连续的重复项,您知道它们来自不同的列表

biglist = list(enumerate(list1)) + list(enumerate(list2))
biglist.sort(key=lambda x: x[1])
matches = [(biglist[i][0], biglist[i + 1][0]) for i in range(len(biglist) - 1) if biglist[i][1] == biglist[i + 1][1]]

答案 2 :(得分:2)

如果没有其他原因而不是验证任何解决方案,那么这个问题的一个强力解决方案是:

[(xi, xp) for (xi, x) in enumerate(list1) for (xp, y) in enumerate(list2) if x==y]

如何优化这一点在很大程度上取决于数据量和内存容量,因此对这些列表的大小有所了解可能会有所帮助。我想我下面讨论的方法对于至少具有数百万个值的列表是有用的。

由于字典访问是O(1),所以似乎值得尝试将第二个列表中的元素映射到它们的位置。假设可以重复相同的元素,collections.defaultdict将很容易让我们构造必要的字典。

l2_pos = defaultdict(list)
for (p, k) in enumerate(list2):
    l2_pos[k].append(p)

表达式l2_pos[k]现在是list2中发生元素k的位置列表。仅保留将这些中的每一个与list1中相应键的位置配对。列表形式的结果是

[(p1, p2) for (p1, k) in enumerate(list1) for p2 in l2_pos[k]]

但是,如果这些结构很大,那么生成器表达式可能会更好。要将名称绑定到上面列表推导中的表达式,您需要编写

values = ((p1, p2) for (p1, k) in enumerate(list1) for p2 in l2_pos[k])

如果你然后迭代values,你就可以避免创建包含所有值的列表的开销,从而减少Python内存管理和垃圾收集的负担,这几乎是解决问题的所有开销。关注。

当您开始处理大量数据时,理解生成器可能意味着有足够的内存来解决您的问题。在许多情况下,它们比列表理解具有明显的优势。

编辑:除非排序的变化有害,否则可以通过使用集合而不是列表来保持位置来进一步加速此技术。这种变化留给读者练习。

答案 3 :(得分:0)

使用dict缩短了查找时间,collections.defaultdict专业化可以帮助您完成簿记。目标是dict,其值是您所追求的索引对。重复值会覆盖列表中的早期值。

import collections

# make a test list
list1 = list('ABCDEFGHIJKLMNOP')
list2 = list1[len(list1)//2:] + list1[:len(list1)//2]

# Map list items to positions as in: [list1_index, list2_index]
# by creating a defaultdict that fills in items not in list1,
# then adding list1 items and updating with with list2 items. 
list_indexer = collections.defaultdict(lambda: [None, None],
 ((item, [i, None]) for i, item in enumerate(list1)))
for i, val in enumerate(list2):
    list_indexer[val][1] = i

print(list(list_indexer.values()))

答案 4 :(得分:0)

这是一个使用defaultdict的简单方法。

<强>鉴于

import collections as ct


lst1 = list("ABCD")
lst2 = list("BDAG")
lst3 = list("EAB")
str1 = "ABCD"

<强>代码

def find_matching_indices(*iterables, pred=None):
    """Return a list of matched indices across `m` iterables."""
    if pred is None:
        pred = lambda x: x[0]

    # Dict insertion
    dd = ct.defaultdict(list)
    for lst in iterables:                                          # O(m)
        for i, x in enumerate(lst):                                # O(n)
            dd[x].append(i)                                        # O(1)

    # Filter + sort
    vals = (x for x in dd.values() if len(x) > 1)                  # O(n)
    return sorted(vals, key=pred)                                  # O(n log n)

<强>演示

在两个列表中找到匹配项(每个OP):

find_matching_indices(lst1, lst2)
# [[0, 2], [1, 0], [3, 1]]

按不同的结果索引排序:

find_matching_indices(lst1, lst2, pred=lambda x: x[1])
# [[1, 0], [3, 1], [0, 2]]

匹配两个以上可迭代项目(可选长度可变):

find_matching_indices(lst1, lst2, lst3, str1)
# [[0, 2, 1, 0], [1, 0, 2, 1], [2, 2], [3, 1, 3]]

<强>详情

字典插入

每个项目都附加到defaultdict的列表中。结果看起来像这样,后来被过滤了:

defaultdict(list, {'A': [0, 2], 'B': [1, 0], 'C': [2], 'D': [3, 1], 'G': [3]})

乍一看,从双for循环中可能会想到时间复杂度为O(n²)。但是,外部循环中的容器列表的长度为m。内部循环处理长度为n的每个容器的元素。我不确定最终的复杂性是什么,但基于this answer,我怀疑它是O(n * m)或至少低于O(n²)。

过滤

过滤掉不匹配(长度为1的列表),并对结果进行排序(主要针对Python中的无序序列&lt; 3.6)。

通过sorted使用timsort算法按某个索引对dict值(列表)进行排序,最坏的情况是O(n log n)。由于dict键插入在Python 3.6+中保留,因此预先排序的项目降低了复杂度O(n)。

总体而言,最佳案例时间复杂度为O(n);最糟糕的情况是O(n log n),如果在Python中使用sorted&lt; 3.6,否则为O(n * m)。

相关问题