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

Python中如何将列表内的numpy数组从(1,n,n)缩减至(n,n)

通用NumPy数组重塑方案

针对将形状为(1, n, n)的NumPy数组转换为(n, n)的需求,以下是几种通用实现方式:

1. 基于数组形状属性的reshape

直接利用数组的shape属性动态获取维度大小,无需硬编码数值:

import numpy as np

# 示例输入数组
arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]])
# 通用重塑操作
arr_reshaped = arr.reshape(arr.shape[1], arr.shape[2])
print(arr_reshaped.shape)  # 输出: (3, 3)

2. 使用squeeze移除单维度

如果数组仅存在长度为1的维度,squeeze()可直接移除所有这类维度,适配性更强(比如也能处理(n, 1, n)这类形状):

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]])
arr_reshaped = arr.squeeze()
print(arr_reshaped.shape)  # 输出: (3, 3)

3. 切片跳过单维度

针对第一个维度固定为1的场景,直接通过切片跳过该维度,获取目标二维数组:

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]])
arr_reshaped = arr[0]
print(arr_reshaped.shape)  # 输出: (3, 3)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:03:30