我有一个二维列表,对于列表中的每个列表,我想打印其索引,对于每个列表中的每个元素,我也想打印其索引。这是我尝试过的:
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
这是为什么呢?我怎样才能让它做我想做的事?
最佳答案
有关 list.index
的帮助:
L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present.
您应该在此处使用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
有关枚举
的帮助:
>>> 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]), ...
关于python - 获取列表中列表元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17131954/