嵌套数组中元素的索引查找方法及库实现问询
嵌套数组目标元素索引查找方案
普通Python列表实现
Python标准库没有直接提供这类嵌套数组索引查找的现成函数,不过可以自己实现递归或迭代的查找逻辑:
def find_nested_index(arr, target): def helper(current, path): for idx, item in enumerate(current): if isinstance(item, list): result = helper(item, path + (idx,)) if result is not None: return result elif item == target: return path + (idx,) return None return helper(arr, ()) # 测试示例 arr = [[[1, 2], [3, 4]], [5, 6]] print(find_nested_index(arr, 2)) # 输出 (0, 0, 1)
NumPy数组实现
如果使用NumPy数组,有现成的方法可以快速完成需求:
先将原列表转为NumPy数组,再通过np.argwhere定位目标元素的索引,最后转为元组格式:
import numpy as np arr_np = np.array([[[1, 2], [3, 4]], [5, 6]]) target = 2 # 获取第一个匹配元素的索引并转为元组 index = tuple(np.argwhere(arr_np == target)[0]) print(index) # 输出 (0, 0, 1)
注意:如果目标元素在数组中多次出现,np.argwhere会返回所有匹配的索引,上述代码仅取第一个匹配项。
内容的提问来源于stack exchange,提问作者Iya Lee
相关产品推荐
相关产品推荐

