【问题标题】:Python Numpy Jupyter Notebook "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" errorPython Numpy Jupyter Notebook \"The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\" 错误
【发布时间】:2023-02-03 04:35:55
【问题描述】:

Code with Error Screenshot

您好,我有一个问题,为什么我会收到此错误消息:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

当我尝试运行此函数并传入 NumPy 数组时:

testValues=np.arange(-5,5,0.01)

def factorial(n):
    if n == 0:
        return 0
    else:
        return 1
        
factorial(testValues)

感谢任何帮助!

【问题讨论】:

    标签: python arrays numpy function jupyter-notebook


    【解决方案1】:

    您的函数设置为接收整数,而不是 NumPy 数组。此外,如果您尝试以递归方式计算阶乘,您将错过对 factorial 函数的递归调用。

    【讨论】:

      【解决方案2】:

      使用 numpy,您将整个 ndarray 传递给您的函数。所以 n 不是一个单一的值。

      您的功能也没有多大意义。如果您告诉我们您的最终目标,也许我们可以更好地帮助您。

      如果您想将您的函数应用于testValues 中的每个数字,您可能需要查看 numpy.vectorize

      np.vectorize(factorial)(testValues)
      

      【讨论】:

        猜你喜欢
        • 2020-07-24
        • 1970-01-01
        • 2021-12-28
        • 2018-10-05
        • 2022-12-01
        • 2022-12-26
        • 2016-03-03
        • 1970-01-01
        • 2018-03-31
        相关资源
        最近更新 更多