python - 将 NumPy 数组中的字符串匹配为另一个数组中的子字符串的更有效方法是什么?
问题描述
我有两个包含字符串的 NumPy 数组。如果该字符串作为子字符串包含在那里,我想使用第一个数组中的每个字符串在第二个数组中搜索。
作为一个非常简单的例子:
import numpy as np
result_list = []
array_1 = np.array(['ab', 'fo', 'ba'])
array_2 = np.array(['lab', 'abc', 'zwf', 'foo', 'bar'])
for word_to_search in array_1:
for potential_word in array_2:
if word_to_search in potential_word:
result_list.append(potential_word)
# delete duplicates
result_list = list(set(result_list))
# result_list = ['lab', 'abc', 'foo', 'bar']
我尝试了基本的 Python 列表以及 NumPy 数组。由于性能原因,后者要好得多,但我仍然认为必须有更好的解决方案。
由于我array_1
有大约 11,000,000 个条目,而我array_2
有大约 300,000 个条目,因此我需要一种非常高效的方法,而我当前的解决方案并非如此。
解决方案
在这一步之后,result.append(potential_word)
你可以跳出那个 for 循环,这样你就没有重复了,而且肯定会节省时间。您还需要为此更改循环的顺序,外循环循环array_2
和内循环array_1
。
import numpy as np
result_list = []
array_1 = np.array(['ab', 'fo', 'ba'])
array_2 = np.array(['lab', 'abc', 'zwf', 'foo', 'bar'])
for potential_word in array_2:
for word_to_search in array_1:
if word_to_search in potential_word:
result_list.append(potential_word)
break
print(result_list)
推荐阅读
- python - 生成未排序的随机数数组
- excel - Excel 数据透视表 - 分别显示年份和月份
- node.js - 在 AWS lambda 中使用 Sharp 模块时出错
- php - 限制对 Azure 存储 Blob 的公共访问
- python - Hangman Python 相同字符的两个实例
- javascript - 获取信息后重定向用户
- json - 使用 Scala 展平 JSON
- r - 为什么 tidyverse 的 mutate/fct_relevel 改变的数据不仅仅是 x-bin 位置?
- html - 如果点击html中的复选框,点击按钮,需要跳转到下一页,但是没有
- maven - 将工件上传到 Artifactory 时,管道写入失败