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

Python中如何根据值的指定部分(如categoryName)对键进行分组并统计数量?

当然可以实现!这是个非常常见的统计需求,用Python就能轻松搞定,我给你一步步拆解怎么做:

实现方案

1. 先明确你的JSON结构(参考示例)

假设你的JSON文件结构大致如下(方便后续代码对应):

[
  {
    "key": "entry_001",
    "Results": [
      {"categoryId": "2674", "categoryName": "software engineer", "score": "1.0377672767639161"},
      {"categoryId": "2675", "categoryName": "data analyst", "score": "0.892"}
    ]
  },
  {
    "key": "entry_002",
    "Results": [
      {"categoryId": "2674", "categoryName": "software engineer", "score": "1.15"}
    ]
  },
  {
    "key": "entry_003",
    "Results": [
      {"categoryId": "2675", "categoryName": "data analyst", "score": "0.76"}
    ]
  }
]

2. 编写Python代码实现统计

我们可以用字典来映射每个categoryName对应的所有键,最后再统计每组的数量:

import json

# 第一步:加载JSON文件
with open('your_json_file.json', 'r', encoding='utf-8') as f:
    json_data = json.load(f)

# 第二步:初始化统计容器,key是categoryName,value是对应键的列表
category_key_stats = {}

# 第三步:遍历所有条目,收集数据
for entry in json_data:
    # 确保当前条目包含key和Results字段(避免报错)
    if 'key' not in entry or 'Results' not in entry:
        continue
    current_key = entry['key']
    # 遍历当前条目的所有Results项
    for result in entry['Results']:
        if 'categoryName' not in result:
            continue
        cate_name = result['categoryName']
        # 把当前key加入对应分类的列表
        if cate_name not in category_key_stats:
            category_key_stats[cate_name] = []
        category_key_stats[cate_name].append(current_key)

# 第四步:输出统计结果
print("=== 分类统计结果 ===")
for cate_name, key_list in category_key_stats.items():
    print(f"* 分类名称:{cate_name}")
    print(f"  关联的键列表:{key_list}")
    print(f"  数量:{len(key_list)}\n")

额外提示

  • 如果你的JSON文件中存在字段缺失的情况(比如某个条目没有key,或者某个Result没有categoryName),代码里的判断逻辑可以帮你跳过这些异常条目,避免程序崩溃。
  • 如果需要把统计结果保存成新的JSON文件,可以在最后添加这段代码:
with open('category_stats_result.json', 'w', encoding='utf-8') as f:
    # 转换为包含数量的结构,比如{"software engineer": {"keys": [...], "count": 2}}
    formatted_result = {
        cate: {"keys": keys, "count": len(keys)} 
        for cate, keys in category_key_stats.items()
    }
    json.dump(formatted_result, f, indent=2, ensure_ascii=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 04:32:33