打印列表中值的位置 Python

Print Location of Value within a list of lists Python

如果我得到一个包含几个列表的列表,并且我想要每次出现的值或字符串的位置,我将如何执行以下代码:

testlist = [[1, 2, 3],[ 5, 3, 1],[ 2, 1, 6]]

for i in [i for i,x in enumerate(testlist) if x == 1]: 打印我

我认为它会打印出来

[0][0]
[2][1]

我不只是想说:

print testlist[0][0]

如何实现?

In [121]: testlist = [[1, 2, 3],[ 5, 3, 1],[ 2, 1, 6]]

In [122]: for i,sub in enumerate(testlist):
   .....:     for j,num in enumerate(sub):
   .....:         if num==1: print("[{}][{}]".format(i,j))
   .....:         
[0][0]
[1][2]
[2][1]

如果您想要一个查找任何通用值的函数:

def search(L, val):
    answer = []
    for i, sub in enumerate(L):
        for j,num in enumerate(sub):
            if num==val:
                answer.append([i,j])
    return answer

如果你想要一条线:

val = 1
answer = [[i,j] for i,sub in enumerate(testlist) for j,num in enumerate(sub) if num==val]
ll = [[1, 2, 3],[ 5, 3, 1],[ 2, 1, 6]]

for k, el in enumerate(ll):
    for i,j in enumerate(el):
        print("row {} column {} elemen {}".format(k, i, j))

row 0 column 0 elemen 1
row 0 column 1 elemen 2
row 0 column 2 elemen 3
row 1 column 0 elemen 5
row 1 column 1 elemen 3
row 1 column 2 elemen 1
row 2 column 0 elemen 2
row 2 column 1 elemen 1
row 2 column 2 elemen 6