在Python中测试给定 NumPy 数组的元素是否为零
在 numpy 中,我们可以借助numpy.all()函数检查给定数组的元素是否为零。在这个函数中传递一个数组作为参数。如果传递数组的任何一个元素为零,则返回 False,否则返回 True 布尔值。
Syntax: numpy.all()
Parameters: An array
Return: A boolean value (True or False)
让我们看看例子:
示例 1:
Python
# import numpy library
import numpy as np
# create an array
x = np.array([34, 56, 89,
23, 69, 980,
567])
# print array
print(x)
# Test if none of the elements
# of the said array is zero
print(np.all(x))
Python
# import numpy library
import numpy as np
# create an array
x = np.array([1, 2, 3,
4, 6, 7,
8, 9, 10,
0, 89, 67])
# print array
print(x)
# Test if none of the elements
# of the said array is zero
print(np.all(x))
输出:
[34,56,89,23,69,980,567]
True
示例 2:
Python
# import numpy library
import numpy as np
# create an array
x = np.array([1, 2, 3,
4, 6, 7,
8, 9, 10,
0, 89, 67])
# print array
print(x)
# Test if none of the elements
# of the said array is zero
print(np.all(x))
输出:
False