python - 在python中找到两个列表之间匹配索引的最快方法?

标签 python python-3.x

我有两个列表

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

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

0 3 2

其中 123 出现在 listB 的第一个元素中,因此结果返回 0,345 出现在 listB 的第四个位置中,因此结果为 3。请注意,两个列表非常巨大(大约 500K 元素),因此 for 循环 太慢。您有建议更快的解决方案吗?这是我的解决方案

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

最佳答案

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

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

关于python - 在python中找到两个列表之间匹配索引的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59004072/

相关文章:

python - 从数据框值创建字典

python-3.x - Geopandas 空间连接 - AttributeError : 'NoneType' object has no attribute 'bounds'

python - 使用 API REST 创建的 GitHub secret 但返回空

python - Python 2.x 中的 BufferedReader 与 Python 3.x

Python-如何同时读取多个文件并记录数据

python - Gensim:如何使用以前的 word2vec 模型重新训练 doc2vec 模型

python - 如何根据元素在它们来自的列表中是否彼此相邻来拆分列表?

python-3.x - 关闭 Jupyter Notebook 输出中的缩写?

python - 强制 timeit 自动选择语句执行的次数

python - 在 Python 中迭代 ndarray