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

如何对列表内的各numpy数组分别求和且空数组返回0

报错原因

  • 你调用np.sum(testGroup, axis=1)时报错,是因为该用法要求输入是结构规整的多维numpy数组,而你的testGroup是长度不一的numpy数组组成的列表,还包含空数组,无法转换为符合要求的二维数组,指定axis参数自然失效。
  • 直接用Python内置sum(testGroup)报错,是因为内置sum对numpy数组列表求和时,默认执行元素级的数组合并操作,不同长度的数组无法对齐,因此抛出ValueError。

解决方案

numpy自带的np.sum()本身就支持对空数组求和返回0,你只需要遍历列表中的每个数组单独求和即可,示例代码如下:

import numpy as np
from numpy import array

testGroup = [array([18]), array([], dtype=int64), array([56, 75, 55, 55]), array([32])]
# 遍历每个数组单独求和
result = [np.sum(arr) for arr in testGroup]
print(result)

运行输出为:

[18, 0, 241, 32]

如果你需要得到numpy数组格式的结果,可以再包一层转换:

result_arr = np.array(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:06:03