Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Numpy数组中查找子列表的索引_Python_Arrays_Numpy - Fatal编程技术网

Python 在Numpy数组中查找子列表的索引

Python 在Numpy数组中查找子列表的索引,python,arrays,numpy,Python,Arrays,Numpy,我正在努力在Numpy数组中查找子列表的索引 a = [[False, True, True, True], [ True, True, True, True], [ True, True, True, True]] sub = [True, True, True, True] index = np.where(a.tolist() == sub)[0] print(index) 这个密码给了我 array([0 0 0 1 1 1 1 2 2 2 2])

我正在努力在Numpy数组中查找子列表的索引

a = [[False,  True,  True,  True],
     [ True,  True,  True,  True],
     [ True,  True,  True,  True]]
sub = [True, True, True, True]
index = np.where(a.tolist() == sub)[0]
print(index)
这个密码给了我

array([0 0 0 1 1 1 1 2 2 2 2])

我无法向自己解释。输出不应该是
数组([1,2])
吗?为什么不是?还有,我如何才能实现这个输出?

如果我理解正确,我的想法如下:

>>> 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]])
>>> np.all(a == sub, axis=1)
array([False,  True,  True])
一种布尔数组,其中每行的
True
/
False
值指示
a
中的值是否等于
sub
中的相应值。(
sub
正在沿此处的行广播。)

np.all(a==sub,axis=1)
为您提供

>>> a == sub
array([[False,  True,  True,  True],
       [ True,  True,  True,  True],
       [ True,  True,  True,  True]])
>>> np.all(a == sub, axis=1)
array([False,  True,  True])
一个布尔数组,对应于
a
中等于
sub
的行

在这个子结果上使用
np.where
可以给出这个布尔数组
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]))
有关您尝试的详细信息:

np.其中(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)

您也可以在不使用numpy的情况下仅对本机python执行此操作

res=[i代表i,v在枚举(a)if all(e==f代表e,f在zip(v,sub))中]

你的代码给了我数组
[0 0 0 1 1 2 2 2]
,而不是
[]
@timgeb你说得对。我更新了这个,实际上
a
的定义也不正确,因为它是一个成形的np数组,对我很有帮助!