如果我理解正确,这是我的想法:
>>> a
array([[False, True, True, True],
[ True, True, True, True],
[ True, True, True, True]])
>>> sub
>>> array([ True, True, True, True])
>>>
>>> result, = np.where(np.all(a == sub, axis=1))
>>> result
array([1, 2])
关于这个解决方案的详细信息:
a == sub
会给你
>>> a == sub
array([[False, True, True, True],
[ True, True, True, True],
[ True, True, True, True]])
一个布尔数组,其中每一行的True
/False
值表示a
中的值是否等于sub
中相应的值。(这里sub
被沿着行广播。)
np.all(a == sub, axis=1)
会给你:
>>> np.all(a == sub, axis=1)
array([False, True, True])
一个布尔数组与a
的行对应,其中的值等于sub
。
在这个子结果上使用np.where
将给出该布尔数组为 True
的索引。
关于您的尝试的详细信息:
np.where(a == sub)
(不需要使用 tolist
)将给出两个数组,它们共同指示数组a == sub
中值为 True
的索引。
>>> np.where(a == sub)
(array([0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]),
array([1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]))
如果将这两个数组合并,您将得到其中
a == sub
为
True
的行/列索引,即:
>>> for row, col in zip(*np.where(a==sub)):
...: print('a == sub is True at ({}, {})'.format(row, col))
a == sub is True at (0, 1)
a == sub is True at (0, 2)
a == sub is True at (0, 3)
a == sub is True at (1, 0)
a == sub is True at (1, 1)
a == sub is True at (1, 2)
a == sub is True at (1, 3)
a == sub is True at (2, 0)
a == sub is True at (2, 1)
a == sub is True at (2, 2)
a == sub is True at (2, 3)
[0 0 0 1 1 1 1 2 2 2 2]
,而不是[]
。 - timgeba
的定义也是不正确的,因为它应该是一个形状为 np 数组。 - Philipp