我有两个数组包含字符串。对于一个数组中的每个字符串,我要检查它是否以第二个数组中的字符串结尾。在
输入:
strings = ['val1', 'val2', 'val3']
ends = ['1', '2', 'al1']
期望输出:
^{pr2}$由于val1
以1
和{
我有以下工作代码:
import numpy as np
strings = ['val1', 'val2', 'val3']
ends = ['1', '2', 'al1']
def buildFunction(ending):
return lambda x: x.endswith(ending)
funcs = list(map(buildFunction, ends))
def end_function_vector(val):
return np.vectorize(lambda f, x: f(x))(funcs, np.repeat(val, len(funcs)))
result = np.array(list(map(end_function_vector, strings)))
并返回所需的输出。在
但是,对于大型数组(~109输出元素),最后一行中的map
需要相当长的时间,因为np.vectorize
和{
这是一个几乎*矢量化的方法,利用^{} -
样本运行-
^{pr2}$*几乎是因为使用了
map
,但由于我们只使用它来获取输入元素的字符串长度,因此与解决我们的情况所需的其他操作相比,它的成本必须是最小的。在Numpy对chararray有这样的操作:
numpy.core.defchararray.endswith()
。在下面的代码可以大大加快速度,但是在创建两个与输出数组大小相同的数组时,确实需要大量内存:
更新:
^{pr2}$如Divakar所述,上述代码可合并为:
相关问题 更多 >
编程相关推荐