首页 > 解决方案 > 列表处理。索引行和列

问题描述

我正在努力对列表数据结构中包含的行和列进行索引。目标是返回 '.' 的坐标。以包含在新列表中的元组的形式。

代码在下面给出为 3x3。答案应该是 [(0,0)]。

lst = [['.', 'x', 'x'],
         ['x', 'x', 'x'],
         ['x', 'x', 'x']]

我写的代码是:

def coor(lst):
    new_lst = []
    for row in lst:
        for col in row:
            if col == '.':
                r = lst.index(row)
                c = lst.index(col)
                new_lst.append((r,c))
    return new_lst

但是,代码是错误的。我想通过调用第一个列表的行索引,它应该返回 0,调用 col 的索引也返回 0。

标签: python

解决方案


enumerate将在这里为您提供帮助:

def coor(lst):
    new_lst = []

    for row_index, row in enumerate(lst):
        for col_index, col in enumerate(row):
            if col == '.':
                new_lst.append((row_index, col_index))

    return new_lst

结果coor(lst)[(0, 0)]

至于为什么您的原始代码首先不起作用,您需要更改c = lst.index(col)c = row.index(col),因为每个col都包含在row.


推荐阅读