Search through a 2-dimensional list without numpy

前端 未结 4 1171
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 03:41

I\'m looking to define a function that accepts two parameters: an int and a list.

If the function finds the integer in the list it returns

4条回答
  •  心在旅途
    2021-01-20 03:44

    Here is my approach:

    def matrix_search(target, matrix):
        for row_index, row in enumerate(matrix):
            try:
                return (row_index, row.index(target))
            except ValueError:
                pass
        raise ValueError('Target {} not found'.format(target))
    

    Sample usage:

    print(matrix_search(4, l))
    

    Notes

    • To search a simple list, use the .index() method
    • The .index() method will either return the index of the element if found or throw a ValueError if not found. In our context, we just ignore this exception and move on to the next row.
    • At the end of the loop, we will throw an exception because the element is not found

提交回复
热议问题