将两个一维numpy数组合并为带来源标记的交替有序二维数组的实现方法
实现代码
你可以通过双指针配合交替选取逻辑实现需求,完整代码如下:
import numpy as np a = np.array([ 7, 9, 12, 15, 17, 22]) b = np.array([ 0, 13, 17, 18]) i = j = 0 res = [] # 确定首个选取的数组 if a[0] < b[0]: current_source = 0 res.append([0, a[i]]) i += 1 else: current_source = 1 res.append([1, b[j]]) j += 1 last_val = res[-1][1] # 交替选取元素 while i < len(a) and j < len(b): next_source = 1 - current_source if next_source == 0: # 跳过a中小于上一个取值的元素 while i < len(a) and a[i] < last_val: i += 1 if i < len(a): res.append([0, a[i]]) last_val = a[i] i += 1 current_source = 0 else: # 跳过b中小于上一个取值的元素 while j < len(b) and b[j] < last_val: j += 1 if j < len(b): res.append([1, b[j]]) last_val = b[j] j += 1 current_source = 1 # 处理剩余未选取的元素 while i < len(a): if a[i] >= last_val: res.append([0, a[i]]) last_val = a[i] i += 1 while j < len(b): if b[j] >= last_val: res.append([1, b[j]]) last_val = b[j] j += 1 # 转换为numpy数组输出 res_np = np.array(res) print(res_np)
运行结果
执行上述代码会输出和预期完全一致的结果:
[[ 1 0] [ 0 7] [ 1 13] [ 0 15] [ 1 17] [ 0 17] [ 1 18] [ 0 22]]
内容的提问来源于stack exchange,提问作者georgehere
相关产品推荐
相关产品推荐

