将 numpy 标量转换为 python 简单的原生(一转)

Convert numpy scalar to python simple native (with one twist)

我有一个函数可以执行一些操作并设置一些 protobuf 值。

现在 protobuf 要求设置的值是 python 本机值而不是 numpy 值。

现在一半的时间使用本机值调用此函数,一半的时间使用 numpy 值。

我需要一种完全可靠的方法来将 numpy 值转换为本机值,同时如果类型已经是 python 本机值则不会引起问题。

我尝试了什么:

使用numpy.asscalar 获取本机值时失败 我曾尝试将其转换为字符串然后再返回,但感觉执行此操作非常缓慢且糟糕。

您可以编写自己的 asscalar(),它会尝试使用 np.asscalar() 并恢复为仅按原样返回值,如果失败:

import numpy as np

def asscalar(v):
    """
    Try converting a numpy array of size 1 to a scalar equivalent, or return
    the value as is.

    Returns:
        A scalar value, if a numpy array of size 1 was given, the value itself
        otherwise. Note that a python list of size 1 will be returned as is.

    Raises:
        A ValueError, if v is a numpy array of size larger than 1.
    """
    try:
        return np.asscalar(v)

    except AttributeError:
        # Not something numpy understands
        return v