繁体   English   中英

在具有 2D 索引的 2D 列表中查找(子)项的索引

[英]Find index of an (sub)item in a 2D list with a 2D index

这不是一个简单的问题,有点棘手并且不知道是否可以在所有限制条件下解决。 所以我的列表中有这个数字,我需要一种方法来检索它的索引,问题是我的列表是一个二维列表,所以我不能真正应用.index()方法。 否则,我必须传入此 2D 列表中的一个 1D 列表。 当我想要的实际上是这个一维列表中的数字的索引时。

我首先找不到子列表的索引(一维列表),因为我所拥有的只是我想要找到索引的数字,我没有子列表。 另一个主要问题是这个相同的数字可以在多个子列表中找到,在这种情况下,找到这个数字将返回多个索引。

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]

我需要我的 output 看起来像:

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)

Output:

[[(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)]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM