我经常编写一些函数/方法,这些变量可以有多种形式,即列表列表、元组列表、元组元组等,所有这些都包含数字,我想将其转换为 numpy 数组,有点像下面这样:
import numpy as np
def my_func(var: 'what-freaking-type-here') -> np.ndarray:
a = np.asarray(var, dtype=np.float64) # type: np.array[np.float] maybe?
return a
基本上,我的问题是如何正确输入它,因为我可以将各种值传递给该函数以最终创建一个二维 float 组(请注意,这只是一个示例,维度和类型应该可以互换):
my_func([[0], [0]])
my_func([(0,), (2.3,)])
my_func(((0,), [2.3,]))
my_func(np.arange(100).reshape(10, 10))
我的做法是在很多地方采用各种值并将它们转换为 numpy 数组,以使函数的使用变得简单直观。但是,我不知道如何正确输入此内容以使用 mypy
进行验证。有什么提示吗?
最佳答案
尝试numpy-stubs: experimental typing stubs for NumPy .
它定义了np.array()
函数的类型,如下所示:
def array(
object: object,
dtype: _DtypeLike = ...,
copy: bool = ...,
subok: bool = ...,
ndmin: int = ...,
) -> ndarray: ...
它接受任何对象
作为内容并返回ndarray
类型。
这是一项正在进行的工作。请报告现阶段是否有效。
还有一个较旧的项目 numpy-mypy 。正如它所指出的,
Quite a few numpy methods are incredibly flexible and they do their best to accommodate to any possible argument combination. ... Although this is great for users, it caused us a lot of problems when trying to describe the type signature for those methods.
它定义了np.array()
函数的类型,如下所示:
def array(object: Any, dtype: Any=None, copy: bool=True,
order: str=None, subok: bool=False,
ndmin: int=0) -> ndarray[Any]: ...
它采用 Any
作为内容(不进行类型检查)并返回由元素类型参数化(通用)的 ndarray
类型。
关于python - 如何输入传递给 numpy.asarray 的变量以生成 2D float 组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54457331/