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

如何使用NumPy实现指定结构的数组拼接并保留列表结构?

Fixing NumPy Array Concatenation for Your Target Structure

Hey there! Let's sort out this array structuring problem you're facing. First, let's break down what's going wrong with your original code, then walk through the right ways to get exactly the structure you want: [[[a,b,c],[1,2,3]],[[a,b,c],[1,2,3]]].

What's Wrong with the Original Code?

Your initial use of np.concatenate has two key issues:

  1. np.concatenate expects its first argument to be a sequence of arrays (like a list or tuple), not two separate array inputs.
  2. Even if fixed to np.concatenate([array, array2]), this would stack the arrays along axis 0 (the default), resulting in a 4x3 array—not the nested 3D structure you need.

Correct Solutions to Get Your Target Structure

First, make sure your inputs are proper NumPy arrays (not just Python lists):

import numpy as np

# Replace these with your actual values for a, b, c
a, b, c = 0, 1, 2

# Convert your initial lists to NumPy arrays
array = np.array([[a,b,c], [a,b,c]])
array2 = np.array([[1,2,3], [1,2,3]])

Method 1: Use np.stack (Cleanest Approach)

np.stack lets you stack arrays along a new axis, which is perfect for pairing corresponding rows from your two arrays:

result = np.stack([array, array2], axis=1)

When you run this, the output will be:

array([[[0, 1, 2],
        [1, 2, 3]],

       [[0, 1, 2],
        [1, 2, 3]]])

This matches exactly the [[[a,b,c],[1,2,3]],[[a,b,c],[1,2,3]]] structure you're after. The axis=1 parameter tells NumPy to pair the first row of array with the first row of array2, and the second row with the second row.

Method 2: List Comprehension (Explicit & Readable)

If you prefer a more hands-on approach, you can manually pair rows with a list comprehension, then convert to a NumPy array:

result = np.array([[array[i], array2[i]] for i in range(array.shape[0])])

This loops through each row index, creates a sublist with the matching rows from array and array2, then converts the entire list of sublists into a 3D NumPy array.

Verify the Structure

To confirm you have the right shape, run print(result.shape)—it should return (2, 2, 3), which means:

  • 2 outer elements (each being a pair of subarrays)
  • 2 subarrays per outer element
  • 3 values per subarray

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:40:33