[英]How to map a linear index to 2D index for array of list in 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.