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

如何将tar.json转为指定格式字典并统计元组元素数量?

实现方案

1. 转换为目标格式字典

根据你提供的数据结构,可通过遍历线路与站点数据、清理站点名称后构建目标字典:

import json
import re

# 加载原始数据
with open('tar.json', "r", encoding='utf-8') as read_file:
    data = json.load(read_file)

# 初始化结果字典
line_stops_dict = {}

# 遍历每条线路数据
for line_item in data["linia"]:
    # 提取线路编号并转为int类型
    line_number = int(line_item["linia"])
    # 处理站点名称,去除末尾的编号后缀
    cleaned_stops = []
    for stop in line_item["przystanek"]:
        stop_name = stop["name"]
        # 正则匹配并移除末尾的"空格+数字"后缀(如'Chmieleniec 02' → 'Chmieleniec')
        cleaned_name = re.sub(r'\s+\d+$', '', stop_name)
        cleaned_stops.append(cleaned_name)
    # 将站点列表转为元组,存入字典
    line_stops_dict[line_number] = tuple(cleaned_stops)

# 验证线路52的结果
print(line_stops_dict.get(52))

2. 统计每个线路的站点数量

直接通过元组的长度属性获取站点数量,遍历字典输出结果:

# 遍历字典统计并打印每个线路的站点数
for line_num, stops_tuple in line_stops_dict.items():
    print(f"线路 {line_num} 站点数量:{len(stops_tuple)}")

关键说明

  • 站点名称清理:使用正则表达式re.sub(r'\s+\d+$', '', stop_name)精准移除名称末尾的编号后缀,避免破坏带空格的正常站点名(如'TAURON Arena Kraków Wieczysta')。
  • 数据类型转换:线路编号转为int类型作为字典键,符合要求格式;站点列表转为元组是因为元组不可变,适合作为字典的静态值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:56:30