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

如何优雅地交错合并NumPy数组?现有实现可优化吗?

Great question! You're right that manually listing each row isn't scalable or elegant—here are three cleaner, more efficient approaches to achieve your desired interleaved array:

Method 1: List Comprehension + Concatenate (Readable & Scalable)

This approach builds small pairs of [x, row] for each row in y, then concatenates them all together. It’s easy to read and works for any number of rows in y:

import numpy as np
x = np.array([1,2,3,4,5])
y = np.array([[4,6,2,6,9], [5,9,8,7,4], [3,2,5,4,9]])

result = np.concatenate([[x], row] for row in y)

Method 2: Slice Assignment (Most Efficient)

Preallocate an empty array of the correct shape, then use slice indexing to fill in x and y rows in one go. This is ideal for large datasets since it avoids extra intermediate arrays:

result = np.empty((2 * len(y), x.size), dtype=x.dtype)
result[::2] = x  # Fill even-indexed rows (0,2,4) with x
result[1::2] = y # Fill odd-indexed rows (1,3,5) with y's rows

Method 3: Tile + Stack + Reshape (Vectorized Operation)

Repeat x to match the number of rows in y, stack it with y along a new axis, then reshape to flatten the pairs into rows:

repeated_x = np.tile(x, (len(y), 1))  # Shape: (3,5)
combined = np.stack([repeated_x, y], axis=1)  # Shape: (3,2,5)
result = combined.reshape(-1, x.size)  # Shape: (6,5)

All three methods will produce your desired output:

array([[1, 2, 3, 4, 5],
       [4, 6, 2, 6, 9],
       [1, 2, 3, 4, 5],
       [5, 9, 8, 7, 4],
       [1, 2, 3, 4, 5],
       [3, 2, 5, 4, 9]])

Content of the question来源于stack exchange,提问作者mocs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:40:37