You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python三层嵌套列表查找指定元素索引返回空列表问题求解

问题解决

错误原因

  • 原代码调用index函数时传入的第二个参数是完整的check_for_test列表,函数内部直接判断整个列表是否存在于内层子列表中,没有匹配项,因此返回全空结果
  • 函数内部循环错误使用全局变量test_list,而非传入的source_list参数,逻辑冗余
  • 遍历方向错误:应该先遍历待查找的目标元素,再去源嵌套列表中匹配,而非反向遍历

修改后可运行代码

test_list =[[[0,0,0,1],[0,0,0,3],[0,0,0,5],[0,0,0,6]],[[0,0,0,4]],[[0,0,0,0],[0,0,0,1]]]
check_for_test = [6,4,1]

def index(source_list, find_list):
    index_finder = []
    # 逐个遍历要查找的目标元素
    for target in find_list:
        # 遍历第一层嵌套列表,i是第一层索引
        for i, second_level in enumerate(source_list):
            # 遍历第二层嵌套列表,j是第二层索引
            for j, item_list in enumerate(second_level):
                if target in item_list:
                    index_finder.append([(i, j)])
                    # 找到匹配后直接跳出当前元素的查找
                    break
            else:
                continue
            break
    return index_finder

deep_index = index(test_list, check_for_test)
print(deep_index)

运行输出

[[(0, 3)], [(1, 0)], [(2, 1)]]

简化列表推导式版本

如果追求代码简洁,也可以用列表推导式实现相同逻辑:

def index(source_list, find_list):
    return [
        [(i, j) for i, second in enumerate(source_list) for j, item in enumerate(second) if target in item]
        for target in find_list
    ]

内容的提问来源于stack exchange,提问作者dd13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 02:54:03