python - 如何输入传递给 numpy.asarray 的变量以生成 2D float 组?

标签 python numpy type-hinting mypy

我经常编写一些函数/方法,这些变量可以有多种形式,即列表列表、元组列表、元组元组等,所有这些都包含数字,我想将其转换为 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/

相关文章:

python - 在 python 中计算二维网格上的一组的有效方法是什么? [下图]

python - 如何使用Python从html字符串中剥离(而不是删除)指定的标签?

python - 通过矩阵与向量元素相乘构建 NXN 矩阵的 Numpy 方法

python - 在 numpy 中,计算一个矩阵,其中每个单元格包含该行中所有其他条目的乘积

clojure - 如何键入提示数组?

python - 错误: 'NoneType' object has no attribute 'call'

python - Kivy 无法从外部 URL 加载图像

python - 在Python中删除二维数组中的最后一个值

Python 输入 : return type with generics like Clazz[T] as in Java Clazz<T>

Python 3.5 类型提示不会导致错误