Search through a 2-dimensional list without numpy

前端 未结 4 1172
伪装坚强ぢ
伪装坚强ぢ 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 04:01

    You can do something like this:

    l = [
             [0, 0, 0, 0, 0, 0, 0, 0, 0],
             [0, 2, 1, 1, 0, 1, 1, 1, 0],
             [0, 1, 0, 1, 0, 0, 0, 1, 0],
             [0, 1, 0, 1, 1, 1, 0, 1, 0],
             [0, 1, 0, 0, 0, 1, 0, 1, 0],
             [0, 1, 1, 1, 0, 1, 0, 1, 0],
             [0, 0, 0, 1, 0, 1, 0, 1, 0],
             [0, 1, 1, 1, 0, 1, 0, 1, 0],
             [0, 1, 0, 0, 0, 0, 0, 1, 0],
             [0, 1, 0, 1, 1, 1, 0, 1, 0],
             [0, 1, 0, 1, 0, 1, 0, 1, 0],
             [0, 1, 1, 1, 0, 1, 1, 4, 0],
             [0, 0, 0, 0, 0, 0, 0, 0, 0]
        ]
    
    def findElement(element, l):
        for i in range(len(l)):
            for j in range(len(l[i])):
                if element==l[i][j]:
                    return (i,j)
        return None
    
    print(findElement(4,l))
    

    Output:

    (11, 7)
    

提交回复
热议问题