python - 获取列表中列表元素的索引

标签 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  #                  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/

相关文章:

list - Prolog - 元素索引

python - Python 请求中没有文件的多部分/表单数据请求

python - 评估数组中的 k 个相邻(正或负)元素

python - 如何抓取所有 ID 具有不同值的所有 <li id=> ?

python - 循环直到每个元素返回 true

python - 将列表中的每个项目添加到 FASTA 文件中特定行的末尾

java - 我的列表中只有最后添加的数组

swift - 不能使用字符串类型的索引下标 NSDictionary 类型的值

java - 如何使用 java 8 lambda 创建内部成员列表?

java - 如何找到其中包含空元素的整数数组的最大元素的索引?