NumPy中的“any”有困难

2024-05-28 20:56:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3,并试图检查array2中元素的sqrt是否在a中。你知道吗

我收到错误:

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

我的代码:

import numpy as np

def mems(a, b):
    a = np.array(a)
    b = np.array(b)
    return np.any(np.sqrt(b) in a)

Tags: ofthean元素value错误withnp
2条回答

您可以使用in1d中的numpy函数

import numpy as np

def mems(a, b):
    return np.any(np.in1d(a, np.sqrt(b)))

但是如果你用非整数做这个,你会得到错误的结果。你知道吗

我猜,返回部分是错误的。试试这个:

import numpy as np

def mems(a, b):
    a = np.array(a)
    b = np.array(b)
    b_sqrt = np.sqrt(b)
    return any(sqrt in a for sqrt in b_sqrt)

print(mems([1, 2, 3, 4, 5], [20, 56]))
print(mems([1, 2, 3, 4, 5], [16, 25, 17, 18]))

输出:

False
True

相关问题 更多 >

    热门问题