Find indices of a value in 2d matrix

前端 未结 5 1773
闹比i
闹比i 2020-12-10 07:35

I have a matrix of the form,

mymatrix=[[1,2,3],[4,5,6],[7,8,9]]

I want to the get the index of, say for example, 9 which is at (2,2).

5条回答
  •  长情又很酷
    2020-12-10 08:31

    You could do this instead of using enumerate. NOT sure at all if this is any faster.

    matrix = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
    needle = 9
    
    matrix_dim = len(matrix[0])
    item_index = 0
    for row in matrix:
        for i in row:
            if i == needle:
                break
            item_index += 1
        if i == needle:
            break
    
    print(int(item_index / matrix_dim), item_index % matrix_dim)
    

    This will take exactly time i * dim(matrix) + (j+1) where the result of the above is i j which could be O(n^2) in the worst case.

提交回复
热议问题