首页 > 解决方案 > 如何键入采用通用数组的numpy函数

问题描述

根据numpy 文档,要声明我应该使用的通用 numpynp.floating[T]类型T = TypeVar("T", bound=npt.NBitBase)。然后 NDarray 采用标量类型。如何将两者结合起来创建一个采用通用浮点数组的函数?以下:

T = TypeVar("T", bound=npt.NBitBase)


def entropy(x: npt.NDArray[np.floating[T]]) -> np.floating[T]:
    return cast(np.floating[T], np.sum(x * np.log(x)))

给我:TypeError: 'type' object is not subscriptable

标签: pythonnumpytype-hintingmypypython-typing

解决方案


推荐阅读