python - 在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)
解决方案
你可以这样试试。我们知道在字典中查找东西是最快的,所以解决方案应该使用字典来完成任务。
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 »
推荐阅读
- node.js - MongoDB 无法等待结果
- label - Zebra ZPL 脚本的水平文本
- angular - 无法使用角度 2+ 获取模板参考值
- security - HDP KYLO 沙箱中的 Kylo 安全实现?
- android - 如何检查设备上是否安装了 WhatsApp?
- wso2 - 具有外部 GLUU OpenId Connect IDP 的 WSO2 身份服务器 - 身份验证方法 client_secret_basic 与 client_secret_post
- ios - 无法更改 UIAlertController 标题和消息
- java - 改造上传 Base64 字符串作为字段 (8MB) 需要 4 分钟
- ruby-on-rails - PostCSS 未加载 SCSS 模块依赖项
- c++ - 为什么按空格字符拆分文件缓冲区不起作用?