【问题标题】:Type hint 2D numpy array类型提示 2D numpy 数组
【发布时间】:2021-06-13 20:21:45
【问题描述】:

作为this question 的后续行动,我有一个函数将返回固定列但可变行的二维numpy.array

import numpy.typing as npt

def example() -> npt.ArrayLike:
    data = np.array([[1,2,3],
                     [4,5,6],
                     ...,
                     [x,y,z]])

我怎样才能明确提示返回的数组将是 3 列 by N(变量)行?

【问题讨论】:

  • Numpy Typing 文档没有说明可能的尺寸。所以也许你目前不能轻易。但是,使用Python new type,您也许可以实现自定义解决方案。取决于你想对类型提示做什么,我猜。
  • 那里有一个答案,指定了numpy数组的形状...
  • @SamuelNLP,在添加 numpy 输入模块之前,该链接是多年前被询问的。我不得不在接受的答案中添加一个很大的免责声明,因为人们一直不赞成。坚持参考当前的numpy 发展。

标签: python numpy type-hinting


【解决方案1】:

目前(2021 年 3 月 16 日)似乎无法对 numpy.ndarray 的形状(或数据类型)进行类型提示。但是,最近有一些针对 numpy 的拉取请求正在朝着这个目标努力。


nptyping package 可以做到这一点,但这不是 numpy 的一部分。

from typing import Any
from nptyping import NDArray

# Nx3 array with Any data type.
NDArray[(Any, 3), Any]

【讨论】:

    猜你喜欢
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 2021-11-10
    • 1970-01-01
    • 2020-11-05
    • 2019-06-27
    • 2015-11-10
    相关资源
    最近更新 更多