You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Numpy如何合并两个不同长度数组按交替顺序生成目标数组

问题解决方案

错误原因

原有代码使用vstack拼接数组时,要求两个输入数组的维度完全匹配,你的数组a长度为5,数组b长度为4,维度不一致所以触发维度不匹配报错。

修改后代码

import numpy as np 

a_multiplier = 3
b_multiplier = 5

a = np.array([5,32,1,4,3])
b = np.array([1,5,11,3])

# 先计算缩放后的数组
a_scaled = a * a_multiplier
b_scaled = b * b_multiplier

# 初始化结果数组,长度为两个数组长度之和
result = np.empty(len(a_scaled) + len(b_scaled), dtype=a.dtype)
# 偶数索引位置放a的缩放结果
result[::2] = a_scaled
# 奇数索引位置放b的缩放结果
result[1::2] = b_scaled

输出验证

运行后打印result即可得到预期结果:

[15  5 96 25  3 55 12 15  9]

内容的提问来源于stack exchange,提问作者georgehere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:45:03