TypeError:ValueError:操作数不能与形状(3,)(2,)-Numpy Array减法一起广播

问题描述 投票:0回答:1

我有以下情况:

  • 我有一个数字列表,例如:
day_list =
[[317, 331, 344],
[305, 326, 340],
[317],
[290, 323],
[311, 325, 345],
[289, 303, 323],
[274, 281, 294, 325],

....
  • 我想从每个内部列表的下一个元素中减去前一个元素,以便将结果附加到“结果”列表中。示例:

第一列表: [317,331,344]

331-317 = 14

344-331 = 13

结果列表: [14,13]

我的代码是:

result = []
sub_result = []
for index, i in enumerate(day_list):
    if len(i) > 1:
        result = []
        for j in range(len(i)-1):
            subtract = np.subtract(np.array(day_list[index][j+1]), np.array(day_list[index][j]))
            result.append(subtract)
        sub_result.append(result)
    else:
        sub_result.append(0)

我收到以下错误:


    ValueError: operands could not be broadcast together with shapes (3,) (2,)

我看到它与我更改数组位置(j + 1)的代码部分有关。而且我不知道如何修复代码并获得正确的结果。

我已经读过很多类似的问题,但是我找不到解决方案。

您能帮忙吗?

Tks,

python numpy numpy-broadcasting
1个回答
0
投票

也许是我纠正的代码中的缩进错误,我现在尝试了此代码,但未收到任何错误:

day_list = [[317, 331, 344],
[305, 326, 340],
[317],
[290, 323],
[311, 325, 345],
[289, 303, 323]]
result = []
sub_result = []
for index, i in enumerate(day_list):
    if len(i) > 1:
        result = []
        for j in range(len(i)-1):
            subtract = np.subtract(np.array(day_list[index][j+1]), np.array(day_list[index][j]))
            result.append(subtract)
        sub_result.append(result)
    else:
        sub_result.append(0)

输出:

[[14, 13], [21, 14], 0, [33], [14, 20], [14, 20]]
© www.soinside.com 2019 - 2024. All rights reserved.