[英]finding the index of elements in nested list
我正在尝试创建一个程序,它将在嵌套列表中查找并存储每个元素的索引。
到目前为止,我已经尝试使用嵌套的迭代器来完成此任务。
以下是我的代码。
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)]
我认为行索引以正确的方式输出,但列索引做了一些奇怪的事情。
我已多次查看代码,但我无法找出它的错误。
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
始终返回列表中元素的第一个索引,因此如果有重复,它将无法工作。 此外,它的性能更差,因为每个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
如果你知道你的表没有锯齿 ,你可以使用itertools.product
:
from itertools import product
def coordinates(tbl):
return list(product(range(len(tbl)), range(len(tbl[0]))))
这是一个numpy
解决方案。
>>> import numpy as np
>>> list(zip(*np.where(np.ones_like(table))))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
如果仔细观察,那么您可能会发现列表中存在重复值,这是导致索引错误的原因。 因此,如果是重复,您可以使用枚举。 枚举将返回元组对象,因此对它进行迭代,这将为您提供预期的输出。
你可以尝试这个 -
def coordinates(table):
target_cell_list = []
for i,row in enumerate(table):
for j in range(len(row)):
target_cell = (i,j)
target_cell_list.append(target_cell)
return target_cell_list
table = [[1, 1, 1], [2, 2, 3], [2, 3, 3]]
print(coordinates(table))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.