gpt4 book ai didi

Python numpy 数组 : check If all elements in array are 0 or 2, true

转载 作者:行者123 更新时间:2023-11-28 19:41:34 25 4
gpt4 key购买 nike

如何在 Python Numpy 中检查数组中的所有元素是否为 0 或 2?例如

if (all elements in c == 0) or   (all elements in c == 2):
This is true
else :
This is False

这意味着如果 c = numpy.array[0,0,2] 它是 true,

但如果 c=numpy.array[0,1,2] 则为 false

谁能给我一段代码?

最佳答案

numpy.isin专为此设计:

import numpy as np

arr1 = np.array([0, 0, 2])
arr2 = np.array([0, 1, 2])

np.isin(arr1, [0, 2]).all()
# True

np.isin(arr2, [0, 2]).all()
# False

当然,这与 ndim 无关:

arr3 = np.random.randint(0, 3, (100, 100))
arr4 = np.random.choice([0,2], (100, 100))

np.isin(arr3, [0, 2]).all()
# False

np.isin(arr4, [0, 2]).all()
# True

关于Python numpy 数组 : check If all elements in array are 0 or 2, true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57248993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com