简体   繁体   English

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

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

I have a 2D array of objects like this:我有一个像这样的二维对象数组:

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

we have object obj which could be any of the objects in the 2D array shown above.我们有 object obj ,它可以是上面显示的二维数组中的任何对象。

How do I get the full index of obj in the 2D array.如何在二维数组中获取 obj 的完整索引。 For example, if obj = o6, the solution should return a[1][2]例如,如果 obj = o6,则解决方案应返回a[1][2]

Using simple loop with enumerate :使用带有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: 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