python - 查找嵌套列表中元素的索引

标签 python python-3.x python-2.7

我正在尝试创建一个程序来查找并存储嵌套列表中每个元素的索引。

到目前为止,我已经尝试使用嵌套的 for 迭代器来完成此任务。

下面是我的代码。

table = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
def coordinates(table):
    target_cell_list = []
    for row in table:
        for column in row:
            target_cell = (table.index(row), row.index(column))
            target_cell_list.append(target_cell)
    return target_cell_list

>>> table = [[1, 1, 1], [2, 2, 3], [2, 3, 3]]
>>> coordinates(table)
# current output
[(0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (1, 2), (2, 0), (2, 1), (2, 1)]

# desired output
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

我认为行索引以正确的方式输出,但列索引在做一些奇怪的事情。

我已经多次查看代码,但我找不到它有什么问题。

最佳答案

嵌套 comprehension使用 enumerate会做:

table = [[1, 1, 1], [2, 2, 3], [2, 3, 3]]

def coordinates(tbl):
    return [(i, j) for i, row in enumerate(tbl) for j, _ in enumerate(row)]
    # or a little shorter
    # [(i, j) for i, row in enumerate(tbl) for j in range(len(row))]

coordinates(table)
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

你的 list.index(elmnt)基于方法失败,因为 index 总是返回列表中元素的 first 索引,所以如果有重复,它就不会工作。此外,它的性能更差,因为每个 index 调用都必须迭代它被调用的列表。 沿着您原来的路线的纯基于循环索引的实现将是:

def coordinates(tbl):
    target_cell_list = []
    for i in range(len(tbl)):
        for j in range(len(tbl[i])):
            target_cell_list.append((i, j))
    return target_cell_list

如果您知道您的表不是 jagged , 你可以使用 itertools.product :

from itertools import product

def coordinates(tbl):
    return list(product(range(len(tbl)), range(len(tbl[0]))))

关于python - 查找嵌套列表中元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53319487/

相关文章:

python-3.x - Python无法通过以下方式连接Jira API

python - docker-compose up : utf-8 codec can't decode byte X

python - 无法转换为 HEX - TypeError : Non-hexadecimal digit found

python - 将 zip 解压缩到内存,解析内容

python - Pyral deleteAttachment 从测试用例定义中删除附件不起作用

python - 有没有办法通过使用后缀号作为迭代器来对不同声明的字符串变量求和?

python - lxml.etree : Start tag expected, '<' 未找到,第 1 行,第 1 列

python - 将数据框转换为字典

Python 3.5.1 - 将变量分配给目标文件夹内的所有文件(文件类型 : . jpg)

python - 如何使用python重命名目录中的文件