检查 Numpy 数组是否包含指定行
在本文中,我们将学习检查指定行是否在 NumPy 数组中。如果给定的列表作为一行存在于 NumPy 数组中,则输出为 True,否则为 False。该列表存在于 NumPy 数组中,这意味着该 numpy 数组的任何行都与给定列表匹配,并且所有元素都按给定顺序排列。这可以通过使用简单的方法来完成,例如使用给定列表检查每一行,但这可以通过使用内置库函数 numpy.array.tolist() 轻松理解和实现。
Syntax: ndarray.tolist()
Parameters: none
Returns: The possibly nested list of array elements.
例子 :
Arr = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]]
and the given lists are as follows :
lst = [1,2,3,4,5] True, as it matches with the row 0.
[16,17,20,19,18] False, as it doesn’t match with any row.
[3,2,5,-4,5] False, as it doesn’t match with any row.
[11,12,13,14,15] True, as it matches with the row 2.
下面是一个例子的实现:
Python3
# importing package
import numpy
# create numpy array
arr = numpy.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]
])
# view array
print(arr)
# check for some lists
print([1, 2, 3, 4, 5] in arr.tolist())
print([16, 17, 20, 19, 18] in arr.tolist())
print([3, 2, 5, -4, 5] in arr.tolist())
print([11, 12, 13, 14, 15] in arr.tolist())
输出 :
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]]
True
False
False
True