You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何返回numpy.vectorize对象而非数值结果?if语句为何需用==?

Python代码问题解答

原代码

import numpy as np

x = [1,2,3]
y = [2,1,2]
def scalar_function(x, y):
    """
    Returns the f(x,y) defined in the problem statement.
    """
    if x <= y:
        s = np.dot(x, y)
    else:
        s = np.divide(x, y)
    return s


print(scalar_function(x, y))

def vector_function(x, y):
    """
    Make sure vector_function can deal with vector input x,y
    """
    a = np.array(x)
    b = np.array(y)
    if a.shape[0] == b.shape[0]:
        vec_fun = np.vectorize(scalar_function(x, y))
    else:
        vec_fun = "x and y are in different dimensions"
    return vec_fun

print(vector_function(x,y))

运行输出

10
<numpy.vectorize object at 0x000001F5790A9B80> ->>> why?? 

问题1:为何vector_function返回numpy.vectorize对象而非实际向量?

你完全用错了np.vectorize:

  • np.vectorize需要传入函数本身,而不是函数的调用结果。你写的scalar_function(x, y)是直接执行函数得到标量10,把这个值传给np.vectorize毫无意义,只会生成一个无作用的向量化对象。
  • 正确流程是:先将scalar_function转化为可处理向量的函数,再用这个新函数去计算输入向量的对应元素结果。

另外你的scalar_function也有问题:如果传入numpy数组,x <= y会得到布尔数组,直接用在if里会触发错误。应该让它只处理单个元素,修正后的完整代码如下:

import numpy as np

x = [1,2,3]
y = [2,1,2]

def scalar_function(x, y):
    # 处理单个元素的逻辑
    if x <= y:
        return x * y
    else:
        return x / y

def vector_function(x, y):
    a = np.array(x)
    b = np.array(y)
    if a.shape[0] == b.shape[0]:
        # 先将标量函数向量化
        vec_func = np.vectorize(scalar_function)
        # 用向量化函数计算结果向量
        return vec_func(a, b)
    else:
        return "x and y are in different dimensions"

print(vector_function(x,y))

运行后会输出array([2., 2., 6.]),这就是你要的实际向量结果。

问题2:为何if语句必须用“==”判断,不能改成“=”?

  • 在Python中,=是赋值运算符,作用是把右边的值赋给左边变量,比如num = 5是给变量num赋值,它本身不会返回布尔值。
  • ==是比较运算符,用来判断左右两边的值是否相等,返回True或False,而if语句需要一个布尔值来决定是否执行后续代码块。

如果把if a.shape[0] == b.shape[0]改成if a.shape[0] = b.shape[0],相当于在if条件里做赋值操作,Python会直接抛出语法错误,因为if条件必须是能产生布尔值的表达式,不能是赋值语句。


内容的提问来源于stack exchange,提问作者Dror Hazan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:55:21