Python: Return 2 ints for index in 2D lists given item

前端 未结 7 1160
轮回少年
轮回少年 2020-12-04 01:31

I\'ve been tinkering in python this week and I got stuck on something.
If I had a 2D list like this:

myList = [[1,2],[3,4],[5,6]]

and

7条回答
  •  难免孤独
    2020-12-04 02:11

    Try this:

    def index_2d(myList, v):
        for i, x in enumerate(myList):
            if v in x:
                return (i, x.index(v))
    

    Usage:

    >>> index_2d(myList, 3)
    (1, 0)
    

提交回复
热议问题