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

如何在Python中遍历CSV层级树结构?

遍历CSV层级树的嵌套循环实现方案

1. 明确CSV数据结构前提

假设你的CSV数据是类似这样的层级结构(对应你提到的父子关系):

父级行有可识别的特征,比如某列(如「层级」)有值,子级对应列为空;或者每行包含「父ID」字段,子级的父ID与对应父级的ID匹配。

实际示例参考:

层级条目名称其他字段
1父级A...
子级A1...
子级A2...
1父级B...
子级B1...

2. 预处理数据:建立父-子映射

先把CSV数据读入内存,整理成「父级→子级列表」的映射关系,方便后续嵌套循环遍历。以下是Python实现示例:

import csv

parent_child_map = {}
current_parent = None

# 读取目标CSV文件
with open('your_tree_data.csv', 'r', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    for row in reader:
        # 判断当前行是否为父级(这里以「层级」列非空作为判断条件)
        if row['层级'].strip():
            current_parent = row
            # 用父级名称作为键,初始化子级列表
            parent_child_map[current_parent['条目名称']] = []
        else:
            # 将子级行添加到当前父级的列表中
            if current_parent:
                parent_child_map[current_parent['条目名称']].append(row)

如果你的CSV用「父ID」关联父子(每行有id和parent_id字段),预处理逻辑可以调整为:

import csv

parent_child_map = {}
all_rows = []

with open('your_tree_data.csv', 'r', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    all_rows = list(reader)

# 筛选所有父级(parent_id为空的行)
parents = [row for row in all_rows if not row['parent_id'].strip()]
# 为每个父级匹配对应的子级
for parent in parents:
    parent_id = parent['id']
    children = [row for row in all_rows if row['parent_id'] == parent_id]
    parent_child_map[parent['条目名称']] = children

3. 嵌套循环遍历处理

有了父-子映射后,直接通过两层循环遍历即可,外层处理父级,内层处理对应子级:

# 外层循环:遍历所有父级
for parent_name, children_list in parent_child_map.items():
    print(f"处理父级:{parent_name}")
    # 内层循环:遍历当前父级的所有子级
    for child_row in children_list:
        print(f"  处理子级:{child_row['条目名称']}")
        # 在这里编写你的具体处理逻辑,比如操作单元格数据
        # process_child_info(child_row)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:18:36