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

如何高效统计含嵌套列表的字典中image键的总数量

嵌套字典统计image键数量最优方案

核心实现逻辑

采用迭代式广度优先遍历所有嵌套节点,既可以规避Python默认递归深度限制问题,又能保证时间复杂度为O(n)(n为所有结构节点总数),是理论最优的实现方式。遍历规则如下:

  • 遇到字典结构时,直接检查是否存在image键,存在则计数+1,同时将字典的所有值加入待遍历队列
  • 遇到列表、元组这类可迭代的非字符串结构时,将所有元素加入待遍历队列继续遍历

可直接运行的代码

def count_image_key(data):
    count = 0
    traverse_queue = [data]
    while traverse_queue:
        current_node = traverse_queue.pop(0)
        if isinstance(current_node, dict):
            if "image" in current_node:
                count += 1
            traverse_queue.extend(current_node.values())
        elif isinstance(current_node, (list, tuple)):
            traverse_queue.extend(current_node)
    return count

# 测试用例(已修正示例中的语法错误)
test_data = {
    "ads": None,
    "results": [
        {
            "height": 1112,
            "image": "https://www.ucsfhealth.org/-/media/project/ucsf/ucsf-health/medical-tests/hero/coombs-test-direct-2x.jpg",
            "source": "Bing"
        },
        {
            "ads": None,
            "results": [
                {
                    "height": 1132,
                    "image": "https://news.images.itv.com/image/file/2164058/img.jpg",
                    "source": "Bing"
                },
                {
                    "ads": None,
                    "results": [
                        {
                            "height": 1112,
                            "image": "http://s1.ibtimes.com/sites/www.ibtimes.com/files/2016/11/11/hiv-test.jpg",
                            "source": "Bing"
                        }
                    ]
                }
            ]
        }
    ]
}

print(count_image_key(test_data))
# 输出结果:3

方案优势

  • 无嵌套层数限制,哪怕嵌套层数超过Python默认递归深度(1000层)也能正常运行
  • 内存占用低,仅存储当前待遍历的节点队列,无冗余内存开销
  • 单次遍历即可拿到结果,执行效率拉满

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:21:02