首页 > 解决方案 > 将 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 个条目,因此我需要一种非常高效的方法,而我当前的解决方案并非如此。

标签: pythonnumpyperformance

解决方案


在这一步之后,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)

推荐阅读