Find indices of a value in 2d matrix

前端 未结 5 1771
闹比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:36

    If you want all of the locations that the value appears at, you can use the following list comprehension with val set to whatever you're searching for

    [(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]
    

    for example:

    >>> mymatrix=[[1,2,9],[4,9,6],[7,8,9]]
    >>> val = 9
    >>> [(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]
    [(0, 2), (1, 1), (2, 2)]
    

    EDIT

    It's not really true that this gets all occurrences, it will only get the first occurrence of the value in a given row.

提交回复
热议问题