使用 2D 索引在 2D 列表中查找(子)项的索引
Find index of an (sub)item in a 2D list with a 2D index
这不是一个简单的问题,有点棘手,不知道是否可以在所有限制条件下解决。
所以我的列表中有这个数字,我需要一种方法来检索它的索引,问题是我的列表是一个二维列表,所以我不能真正应用 .index()
方法。否则,我必须传入此二维列表中的一个一维列表。当我想要的实际上是这个一维列表中的数字索引时。
我找不到子列表的索引(一维列表),因为我只有我想找到索引的数字,我没有子列表。
另一个主要问题是,同一个数字可以在多个子列表中找到,在这种情况下,找到这个数字将 return 不止一个索引。
my2D_list =[[5, 4, 8, 3, 6], [3, 5, 0, 6, 7], [9, 8, 0, 1, 2], [9, 7, 4, 8, 4], [7, 2, 0, 5, 3]]
#I placed in this list the numbers I need to find the index of in my2D_list.
items_to_find_the_index_of= [9, 8, 8, 0, 3]
我需要我的输出看起来像:
9 = my2D_list[2][0] and my2Dlist[3][0]
items_to_find_the_index_of 列表中的所有号码都一样。
我什至不知道这个问题是否真的可以按照我需要的方式解决,但感谢您花时间和精力帮助我找到解决方法。
肉巴。
items_to_find_the_index_of = [9, 8, 8, 0, 3]
index_container = []
for item in items_to_find_the_index_of:
indexes = []
for index, sub_lst in enumerate(my2D_list):
try:
indexes.append((index, sub_lst.index(item)))
except ValueError:
pass
index_container.append(indexes)
print(index_container)
输出:
[[(2, 0), (3, 0)], [(0, 2), (2, 1), (3, 3)], [(0, 2), (2, 1), (3, 3)], [(1, 2), (2, 2), (4, 2)], [(0, 3), (1, 0), (4, 4)]]
这不是一个简单的问题,有点棘手,不知道是否可以在所有限制条件下解决。
所以我的列表中有这个数字,我需要一种方法来检索它的索引,问题是我的列表是一个二维列表,所以我不能真正应用 .index()
方法。否则,我必须传入此二维列表中的一个一维列表。当我想要的实际上是这个一维列表中的数字索引时。
我找不到子列表的索引(一维列表),因为我只有我想找到索引的数字,我没有子列表。 另一个主要问题是,同一个数字可以在多个子列表中找到,在这种情况下,找到这个数字将 return 不止一个索引。
my2D_list =[[5, 4, 8, 3, 6], [3, 5, 0, 6, 7], [9, 8, 0, 1, 2], [9, 7, 4, 8, 4], [7, 2, 0, 5, 3]]
#I placed in this list the numbers I need to find the index of in my2D_list.
items_to_find_the_index_of= [9, 8, 8, 0, 3]
我需要我的输出看起来像:
9 = my2D_list[2][0] and my2Dlist[3][0]
items_to_find_the_index_of 列表中的所有号码都一样。 我什至不知道这个问题是否真的可以按照我需要的方式解决,但感谢您花时间和精力帮助我找到解决方法。
肉巴。
items_to_find_the_index_of = [9, 8, 8, 0, 3]
index_container = []
for item in items_to_find_the_index_of:
indexes = []
for index, sub_lst in enumerate(my2D_list):
try:
indexes.append((index, sub_lst.index(item)))
except ValueError:
pass
index_container.append(indexes)
print(index_container)
输出:
[[(2, 0), (3, 0)], [(0, 2), (2, 1), (3, 3)], [(0, 2), (2, 1), (3, 3)], [(1, 2), (2, 2), (4, 2)], [(0, 3), (1, 0), (4, 4)]]