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

2019-01-15 18:34发布

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 I did this

>>>myList.index([3,4])

it would return

1

However, I want the index of something in side one of the lists, like this

    >>>myList.index(3)

and it would return

1, 0

Is there anything that can do this?

Cheers

7条回答
啃猪蹄的小仙女
2楼-- · 2019-01-15 19:16

Using simple genexpr:

def index2d(list2d, value):
    return next((i, j) for i, lst in enumerate(list2d) 
                for j, x in enumerate(lst) if x == value)

Example

print index2d([[1,2],[3,4],[5,6]], 3)
# -> (1, 0)
查看更多
登录 后发表回答