Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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矩阵查找索引_Python_Arrays_Matrix - Fatal编程技术网

Python矩阵查找索引

Python矩阵查找索引,python,arrays,matrix,Python,Arrays,Matrix,我的代码有以下问题,我想在2d数组中搜索一个特定的数字,并返回出现这个数字的所有索引 matrix = [[0]*10 for _ in range(10)] # Populate the matrix with some digit that I would like to search later on matrix[0][0], matrix[1][2:5], matrix[3][2] = 1, [1 for x in range(4)], 1 # This actually loo

我的代码有以下问题,我想在2d数组中搜索一个特定的数字,并返回出现这个数字的所有索引

matrix = [[0]*10 for _ in range(10)]

# Populate the matrix with some digit that I would like to search later on

matrix[0][0], matrix[1][2:5], matrix[3][2] = 1, [1 for x in range(4)], 1

# This actually looks as follow

[[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

现在我想找到矩阵中出现1的所有索引

[(index, row.index(1)) for index, row in enumerate(matrix) if 1 in row]
[(0, 0), (1, 2), (3, 2)]

这实际上只返回第一行中的第一个实例。我也尝试了两个for循环,但行为是一样的


任何建议都值得赞赏

以下给出了矩阵中元素等于1的所有指数:

[(row,column) for row in range(10) for column in range(10) if matrix[row][column]==1]
输出:

[(0, 0), (1, 2), (1, 3), (1, 4), (1, 5), (3, 2)]

索引仅返回数组中第一次出现的值

如果要使用
index()
可以做的是,当您找到一行中第一个值的
偏移量
时,在
数组[offset+1://code>上调用相同的值,直到没有更多值为止

另一方面,更简单的版本是@joostblack的答案,它只是一个接一个地抓取整个数组