簡體   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