Python 获取列表中列表中元素的索引
我有一个二维列表,对于列表中的每个列表,我想打印它的索引,对于每个列表中的每个元素,我也想打印它的索引。以下是我尝试过的:Python 获取列表中列表中元素的索引,python,list,indexing,Python,List,Indexing,我有一个二维列表,对于列表中的每个列表,我想打印它的索引,对于每个列表中的每个元素,我也想打印它的索引。以下是我尝试过的: 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 #
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
为什么呢?我怎样才能让它做我想做的 有关
列表索引的帮助:
L.index(值,[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
有关枚举的帮助信息
:
>>> 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]), ...
有关列表索引的帮助信息: L.index(值,[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
有关枚举的帮助信息:
>>> 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]), ...
.index(i)
提供第一次出现的i
的索引。因此,您总是可以找到相同的索引。。索引(i)
为您提供第一次出现的i
的索引。因此,您总是会找到相同的索引。它不会这样工作,因为list.index
在找到与您的搜索值相等的第一个值时会短路。它不会这样工作,因为list.index
在找到与您的搜索值相等的第一个值时会短路。@AshwiniChaudhary为什么不做帮助(枚举)
对于beginners@jamylak唯一的原因是enumerate的输出。
的输出比help(enumerate)
的输出更容易复制,后者从Vi
开始。虽然在IPython上我通常更喜欢enumerate?
@AshwiniChaudhary为什么不直接做help(enumerate)
这对于用户来说要简单得多beginners@jamylak唯一的原因是enumerate的输出。uuu doc\uuu
比从Vi
开始的help(enumerate)
的输出更容易复制。虽然在IPython上我通常更喜欢enumerate?
。