簡體   English   中英

如何在二維列表中獲取 object 的完整索引(Python)

[英]How to get the full index of an object in a 2D list (Python)

我有一個像這樣的二維對象數組:

a = [
[o1, o2, o3],
[o4, o5, o6],
[o7, o8, o9],
]

我們有 object obj ,它可以是上面顯示的二維數組中的任何對象。

如何在二維數組中獲取 obj 的完整索引。 例如,如果 obj = o6,則解決方案應返回a[1][2]

使用帶有enumerate的簡單loop

a = [[1,2,3], [4,5,6], [7,8,9]]

# element that you want to find
b = 2

for i,x in enumerate(a):
    if b in x:
        index_2d = (i, x.index(b))

Output:

 >>> print(index_2d) (0, 1) >>> print(a[index_2d[0]][index_2d[1]]) 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM