如何同步两个不同长度的数组?

问题描述

让我们考虑两个包含索引的数组:

x = [0,1,2,3,4,5...]
y = [0,6,9,12,...]

这些数组的长度可能略有不同,大约最多 3 个索引。 在本例中,我们假设 len(x) = len(y) - 1 我想返回同步的 x,它将被 1 个条目扩展,以便这些数组仍然相互对应 (x[n]=y[n]+3)。 我想出了使用 np.searchsorted 方法的想法,但它不起作用:

def synchronize_array(self,arr: np.ndarray) -> np.ndarray:
    sync_idx = np.searchsorted(arr,BASE_ARR)
    sync_idx[sync_idx >= len(arr)] = len(arr) - 1
    return arr[sync_idx]

Sync_idx 在这种情况下是 [0,n-1,...] 有什么方法可以同步这些数组吗?

解决方法

synchronized 的含义不清楚,但您可以遍历两个数组,用 itertools.zip_longest 的默认值填充最短的数组

from itertools import zip_longest

x = [0,1,2,3,4,5]
y = [0,6,9,12]

xy = zip_longest(x,y,fillvalue=0)
print(list(xy))

产生什么

[(0,0),(1,3),(2,6),(3,9),(4,12),(5,0)]

干杯!