1

我有一个二维列表,对于列表中的每个列表,我想打印它的索引,对于每个列表中的每个元素,我还想打印它的索引。这是我尝试过的:

l = [[0,0,0],[0,1,1],[1,0,0]]

def Printme(arg1, arg2):
    print arg1, arg2

for i in l:
    for j in i:
        Printme(l.index(i), l.index(j))

但输出是:

0 0  # I was expecting: 0 0
0 0  #                  0 1
0 0  #                  0 2
1 0  #                  1 0
1 1  #                  1 1
1 1  #                  1 2
2 0  #                  2 0
2 1  #                  2 1
2 1  #                  2 2

这是为什么?我怎样才能让它做我想做的事?

4

2 回答 2

1

帮助list.index

L.index(value, [start, [stop]]) -> integer -- 返回值的第一个索引。如果值不存在,则引发 ValueError。

你应该enumerate()在这里使用:

>>> l = [[0,0,0],[0,1,1],[1,0,0]]
for i, x in enumerate(l):
    for j, y in enumerate(x):
        print i,j,'-->',y
...         
0 0 --> 0
0 1 --> 0
0 2 --> 0
1 0 --> 0
1 1 --> 1
1 2 --> 1
2 0 --> 1
2 1 --> 0
2 2 --> 0

帮助enumerate

>>> print enumerate.__doc__
enumerate(iterable[, start]) -> iterator for index, value of iterable

Return an enumerate object.  iterable must be another object that supports
iteration.  The enumerate object yields pairs containing a count (from
start, which defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list:
    (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
于 2013-06-16T09:46:33.957 回答
0

.index(i)给你第一次出现的索引i。因此,您总是会找到相同的索引。

于 2013-06-16T09:47:42.993 回答