首页 > 解决方案 > 在python中找到两个列表之间匹配索引的最快方法?

问题描述

我有两个列表

listA = ['123', '345', '678']
listB = ['ABC123', 'CDE455', 'GHK678', 'CGH345']

我想找到与listA中每个元素匹配的listB的位置。例如,预期输出是

0 3 2

where123出现在 listB 的第一个元素中,因此结果返回 0,345出现在 listB 的第四个位置,因此为 3。请注意,两个列表中的元素数量非常大(大约 500K 个元素),因此for loop太慢了。你有什么更快的解决方案吗?这是我的解决方案

for i in range (len(listA)):
    for j in range (len(listB)):
        if listA[i] in listB[j]:
            print ('Postion ', j)

标签: pythonpython-3.x

解决方案


你可以这样试试。我们知道在字典中查找东西是最快的,所以解决方案应该使用字典来完成任务。

In [1]: import re                                                                        

In [2]: listA = ['123', '345', '678']                                                    

In [3]: listB = ['ABC123', 'CDE455', 'GHK678', 'CGH345']                                 

In [4]: # Mapping b/w number in listB to related index                                   

In [5]: mapping = {re.sub(r'\D+', '', value).strip(): index for index, value in enumerate(listB)}                                                                         

In [6]: mapping # Print mapping dictionary                                               
Out[6]: {'123': 0, '455': 1, '678': 2, '345': 3}

In [7]: # Find the desired output                                                        

In [8]: output = [mapping.get(item) for item in listA]                                   

In [9]: output                                                                           
Out[9]: [0, 3, 2]

In [10]:   

Attached screenshot »

enter image description here


推荐阅读