【问题标题】:How to synchronize two arrays with different length?如何同步两个不同长度的数组?
【发布时间】:2021-03-29 08:14:07
【问题描述】:

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

x = [0,1,2,3,4,5...]
y = [0,3,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, n-1, n-1, ...] 有什么方法可以同步这些数组吗?

【问题讨论】:

  • 你希望x中的扩展元素取什么值?
  • 在我看来是y[n]=3*x[n],而不是x[n]=y[n]+3
  • 这些数组正在存储其他数组的索引。我不能假设 y[n] 和 x[n] 之间存在固定差异

标签: python arrays numpy synchronize


【解决方案1】:

不清楚你所说的同步是什么意思,但你可以迭代两个数组,用itertools.zip_longest填充最短的数组

from itertools import zip_longest

x = [0, 1, 2, 3, 4, 5]
y = [0, 3, 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)]

干杯!

【讨论】:

  • 好吧,我想这可能会有所帮助!谢谢;)
猜你喜欢
  • 2015-09-09
  • 2014-01-07
  • 2012-07-29
  • 2016-02-23
  • 2013-04-02
  • 2019-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
相关资源
最近更新 更多