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