Search through a 2-dimensional list without numpy

前端 未结 4 1168
伪装坚强ぢ
伪装坚强ぢ 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:54

    The target will always show up only once and will always be contained in the list

    You can use enumerate to enumerate the outer lists and the elements of the inner lists.

    def coords(lst, find):
        return next((i, j) for i, sub in enumerate(lst)
                           for j, x in enumerate(sub)
                           if x == find)
    

    Demo with your list l:

    >>> coords(l, 2)
    >>> (1, 1)
    >>> coords(l, 1)
    >>> (1, 2)
    

    In case you later want to adapt the function to work properly if the target is not in the list, remember that next takes an optional default argument.

提交回复
热议问题