如何检查数组是否在Python中的另一个数组中 [英] How to check if an array is in another array in Python
问题描述
我认为in
对此会有所帮助,但在不应该使用的地方返回true.例如:
I thought that in
would be good for this but it returns true in places where it shouldn't. For example:
import numpy as np
a = np.array([])
for i in range(3):
for j in range(3):
a = np.append(a,[i,j])
a = np.reshape(a,(9,2))
print(a)
print([[0,40]] in a)
将打印为真.我不明白为什么会这样...是因为列表中有0?我希望只有在整个数组都在列表中的情况下才能显示true.
will print true. I cannot understand why it does this... is it because 0 is in the list? I'd like to have something that only prints true if the entire array is in the list.
我想要我的清单
[[0,1],
[0,2]]
,并且仅当其中完全是[0,x]
(相同形状的相同顺序)时才返回true.
and only return true if exactly [0,x]
(same shape same order) is in it.
推荐答案
您可以这样做:
([0, 40] == a).all(1).any()
第一步是计算匹配位置的2D布尔数组.然后,找到所有元素都为真的行.然后检查是否有任何行完全匹配.
The first step is to compute a 2D boolean array of where the matches are. Then you find the rows where all elements are true. Then you check if any rows are fully matching.
这篇关于如何检查数组是否在Python中的另一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!