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

如何用纯Numpy实现从起始长度生成递减零数组列表?

纯NumPy实现生成不同长度零数组的集合

需求说明

需要生成如下结构的NumPy集合(避免使用Python普通列表):

[array([0, 0, 0, 0, 0, 0, 0])
 array([0, 0, 0, 0, 0, 0])
 array([0, 0, 0, 0, 0])
 array([0, 0, 0, 0])
 array([0, 0, 0])
 array([0, 0])
 array([0])]

当前实现依赖Python列表转换,希望找到纯NumPy的解决方案。

当前实现(依赖列表转换)

import numpy as np

# 每个子数组的长度
lengths = [7, 6, 5, 4, 3, 2, 1]

# 创建生成指定长度零数组的ufunc
zeros_array = np.frompyfunc(lambda x: np.zeros(x, dtype=int), 1, 1)

# 转换为Python列表得到结果
arrays_list = list(zeros_array(lengths))

print(arrays_list)

纯NumPy解决方案

由于NumPy原生面向同构数组,这类包含不同长度子数组的异构结构需要用object dtype的NumPy数组存储。以下是纯NumPy实现:

import numpy as np

# 定义各子数组长度(可直接用NumPy数组或原列表)
lengths = np.array([7, 6, 5, 4, 3, 2, 1])

# 创建空的object类型NumPy数组,用于存储不同长度的零数组
result = np.empty(lengths.size, dtype=object)

# 通过NumPy索引循环赋值,全程不依赖Python列表操作
for idx in np.arange(lengths.size):
    result[idx] = np.zeros(lengths[idx], dtype=int)

print(result)

说明

  • 该方案直接生成object dtype的NumPy数组,所有操作均基于NumPy API,无需转换为Python列表。
  • object dtype是NumPy中存储异构数据的标准方式,允许每个元素为任意Python对象(此处为不同长度的NumPy数组)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:27:14