Python:给定项目的2D列表中的索引返回2个整数

Sam*_*man 10 python nested-lists

这个星期我一直在修补python,我陷入了困境.如果我有这样的2D列表:myList = [[1,2],[3,4],[5,6]]

我这样做了

myList = [[1,2],[3,4],[5,6]]
Run Code Online (Sandbox Code Playgroud)

它会回来

>>>myList.index([3,4])
Run Code Online (Sandbox Code Playgroud)

但是,我想要列表中的某些内容的索引,就像这样

1
Run Code Online (Sandbox Code Playgroud)

它会回来的

    >>>myList.index(3)
Run Code Online (Sandbox Code Playgroud)

有什么可以做到这一点?

干杯

Mar*_*ers 15

试试这个:

def index_2d(myList, v):
    for i, x in enumerate(myList):
        if v in x:
            return (i, x.index(v))
Run Code Online (Sandbox Code Playgroud)

用法:

>>> index_2d(myList, 3)
(1, 0)
Run Code Online (Sandbox Code Playgroud)


kev*_*pie 5

如果您正在进行多次查找,您可以创建一个映射。

>>> myList = [[1,2],[3,4],[5,6]]
>>> d = dict( (j,(x, y)) for x, i in enumerate(myList) for y, j in enumerate(i) )
>>> d
{1: (0, 0), 2: (0, 1), 3: (1, 0), 4: (1, 1), 5: (2, 0), 6: (2, 1)}
>>> d[3]
(1, 0)
Run Code Online (Sandbox Code Playgroud)