Skip to main content
 首页 » 编程设计

Python:如何从 2 个数组中找到唯一的元素模式

2024年11月01日11lidabo

我有两个 numpy 数组,A 和 B:

A = ([1, 2, 3, 2, 3, 1, 2, 1, 3]) 
B = ([2, 3, 1, 2]) 

其中 B 是 A 中的唯一模式。

我需要输出 A 的所有元素,它们不存在于 B 中。

Output = ([1, 2, 3, 1, 3]) 

请您参考如下方法:

最简单的是使用 Python 的内置函数,即字符串类型:

A = "123231213" 
B = "2312" 
result = A.replace(B, "") 

要有效地将 numpy.array 转换为 str,请使用这些函数:

x = numpy.frombuffer("3452353", dtype="|i1") 
x 
array([51, 52, 53, 50, 51, 53, 51], dtype=int8) 
x.tostring() 
"3452353" 

(*) 因此混淆了 ascii 代码 (1 != "1"),但子字符串搜索将正常工作。您的数据类型最好适合一个字符,否则您可能会得到错误的匹配。

总结起来,一个快速的 hack 看起来像这样:

A = numpy.array([1, 2, 3, 2, 3, 1, 2, 1, 3]) 
B = numpy.array([2, 3, 1, 2]) 
numpy.fromstring(A.tostring().replace(B.tostring(), ""), dtype=A.dtype) 
array([1, 2, 3, 1, 3]) 
# note, here dtype is some int, I'm relying on the fact that: 
# "1 matches 1" is equivalent to "0001 matches 00001" 
# this holds as long as values of B are typically non-zero. 
# 
# this trick can conceptually be used with floating point too, 
# but beware of multiple floating point representations of same number 

深入解释:

假设 A 和 B 的大小是任意的,naive approach以二次时间运行。然而更好的是,概率算法退出,例如 Rabin-Karp ,它依赖于滑动窗口哈希。

这是面向文本的函数的主要原因,例如 xxx in str 或 str.replace 或 re 将比自定义函数快得多numpy 代码。

如果你真的需要这个功能与numpy集成,你总是可以写一个扩展,但这并不容易:)