在多维列表上使用index()

Man*_*eep 7 python

对于一维列表,项目的索引如下所示:

 a_list = ['a', 'b', 'new', 'mpilgrim', 'new']
 a_list.index('mpilgrim')
Run Code Online (Sandbox Code Playgroud)

2或n维列表的等价物是什么?

编辑:我添加了一个例子来澄清:如果我有一个3维列表如下

b_list = [
          [1,2],
          [3,4],
          [5,6],
          [7,8]
         ],
         [
          [5,2],
          [3,7],
          [6,6],
          [7,9]
         ]
Run Code Online (Sandbox Code Playgroud)

现在假设我想在此列表中标识某个值.如果我知道第一和第二个维度的索引但不知道我想要的值的第零个索引,我该如何找到第零个索引?

会是这样的:

  target_value = 7
  b_list[0].index(target_value)
Run Code Online (Sandbox Code Playgroud)

输出为整数:0

Riv*_*vka 13

我不知道有一种自动方式,但是如果

a = [[1,2],[3,4],[5,6]]

而你想找到3的位置,你可以这样做:

x = [x for x in a if 3 in x][0]

print 'The index is (%d,%d)'%(a.index(x),x.index(3))

输出是:

The index is (1,0)

  • 嘿,这很好,但如果项目不在列表中,我会超出范围异常.有什么好方法可以处理吗? (4认同)

utd*_*mir 7

对于二维列表; 你可以遍历行并使用.index函数来查找项目:

def find(l, elem):
    for row, i in enumerate(l):
        try:
            column = i.index(elem)
        except ValueError:
            continue
        return row, column
    return -1

tl = [[1,2,3],[4,5,6],[7,8,9]]

print(find(tl, 6)) # (1,2)
print(find(tl, 1)) # (0,0)
print(find(tl, 9)) # (2,2)
print(find(tl, 12)) # -1
Run Code Online (Sandbox Code Playgroud)


小智 5

多维列表只是一个列表,其中包含更多列表.所以它的指数就是列表本身.

a = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
print a.index([2, 3, 4])
# prints 1
Run Code Online (Sandbox Code Playgroud)