新版本numpy.subtract产生的问题及解决方法

报错信息:ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (5,) + inhomogeneous part.

问题分析:

产生这个错误的原因目前猜测是因为新版本的numpy(我的是1.25.2)再subtract时对list进行了一些保护,可以尝试降版本到1.21.6来解决问题,也可以通过下列方式来避免问题。

import numpy as np

original_list = [3, 5, 7, np.array([9, 2, 4]), np.array([6, 8, 1])]
c = np.subtract(original_list,1)
print(c)

执行上述代码就会触发下列错误:

Traceback (most recent call last):
  File "path", line XX, in <module>
    c = np.subtract(original_list,1)
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (5,) + inhomogeneous part.

解决方法:

思路:复制一个元素全为1的列表,再逐位相减

import numpy as np

def copy_list(source_list):
    if isinstance(source_list, list):
        new_list = []
        for item in source_list:
            new_list.append(copy_list(item))
        return new_list
    else:
        return 1

original_list = [3, 5, 7, np.array([9, 2, 4]), np.array([6, 8, 1])]
new_list = copy_list(original_list)
c = [original_list[i]-new_list[i] for i in range(0,len(original_list))]

print(new_list)
print(c)

结果正确输出:

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值