python - Numpy 连接 + 合并一维数组

标签 python arrays performance numpy

我需要连接数组,但如果它们重叠,还需要将 A 的结尾与 B 的开头合并。

[1, 2, 4] + [2, 4, 5] -> [1, 2, 4, 5]
[1, 2, 4] + [2, 5, 4] -> [1, 2, 4, 2, 5, 4]
[1, 2, 4] + [1, 2, 4, 5] -> [1, 2, 4, 5]

注意:必须保留元素的顺序,[4, 5] 与 [5, 4] 不同。

注2:这道题也可以这样理解:我们需要对A进行尽可能短的扩展,使得输出以B结尾。

当然,我可以遍历第二个数组并逐个元素进行比较,但我正在寻找一个不错的 Numpy 解决方案。

最佳答案

原来是理解错了问题。问题是根据我的理解:

Two item suffix of A matches 2 item prefix of B:
[1, 2, 4] +
   [2, 4, 5] =>
[1, 2, 4, 5]

No suffix of A matches a prefix of B:
[1, 2, 4] + 
         [2, 5, 4] -> 
[1, 2, 4, 2, 5, 4]

然后我们可以使用这个非常低效的函数:

def merge(A,B):
    i = 0
    m = 0
    # Find largest suffix of A that matches the prefix of B with the same length
    while i <= len(A):
        if A[-i:] == B[:i] and i > m:
            m = i
        i += 1
    return A + B[m:]

关于python - Numpy 连接 + 合并一维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57722109/

相关文章:

javascript - 如何将相同的值放入同一数组元素中

java - 在 Android、Eclipse 中打印字符串数组

sql - Spark数据集错误: Both sides of this join are outside the broadcasting threshold and computing it could be prohibitively expensive

performance - Haxe 编译代码性能

python - 将字符串转换为时间 (H :M:S) so I can subtract them

Python 2.5.2 和 Solaris 8 (gcc 3.4.2) 构建问题

python - 在 Pygame.mixer 的声音结尾处防止 "popping"

java - 如何在ArrayList中存储二维整数数组?

c# - 最优化使用多个 Where 语句

python - 如何在 dataframe python 中创建累计和?