为什么我使用lambda表达式Python在这个ndarray创建中得到一个IndexError

时间:2017-05-26 23:19:32

标签: python numpy lambda

代码如下:

import numpy as np

def f(x):
    assert type(x) is np.ndarray
    return np.fromfunction(lambda i: np.sum(x[:i + 1]), (x.size,))


print(f(np.array((1, 2, 3))))

IndexError: failed to coerce slice entry of type numpy.ndarray to integer

我希望结果是[1,1 + 2,1 + 2 + 3] = [1,3,6]。如果我将f的返回行更改为:

return np.fromfunction(lambda i: np.sum(x[:int(i) + 1]), (x.size,))

我明白了:

TypeError: only length-1 arrays can be converted to Python scalars

我只是将i映射到常量,我应该取值0,...,x.size - 1,所以我在这里看不到什么错误。

0 个答案:

没有答案