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

Python递归拆分数值区间生成嵌套列表树结构的实现问题

解决方案

你可以无需依赖第三方库,通过两种方式实现目标嵌套树结构:

方案1:修改原有递归函数直接生成嵌套树

直接在原有拆分逻辑的基础上调整返回值,拆分的同时直接构造嵌套结构,不需要额外处理输出文件:

data = [[0, 250_000_000]]
cycle = 10
Finale_variants_in_file = 200

def divider(start, stop, patch, cycle):
    Sliced_list = []
    i = 1
    for t in range(cycle):
        if i == 1:
            left = start
            right = start + patch
            Sliced_list.append([left, right])
        elif i == cycle:
            left = start + (((i - 1) * patch) + 1)
            right = stop
            Sliced_list.append([left, right])
        else:
            left = start + (((i - 1) * patch) + 1)
            right = start + (i * patch)
            Sliced_list.append([left, right])
        i += 1
    return Sliced_list

def build_nested_tree(contig, cycle, threshold):
    start, stop = contig
    interval = stop - start
    patch = interval // cycle
    # 区间小于阈值无需拆分,直接返回当前区间
    if patch < threshold:
        return contig
    # 生成子区间后递归构造每个子节点的嵌套结构
    children = divider(start, stop, patch, cycle)
    nested_children = [build_nested_tree(child, cycle, threshold) for child in children]
    # 返回结构为 [父区间, 子节点1, 子节点2, ... 子节点10]
    return [contig] + nested_children

# 调用生成最终嵌套树
root = data[0]
nested_tree = build_nested_tree(root, cycle, Finale_variants_in_file)
# 可直接打印或写入文件
print(nested_tree)

方案2:从已有的输出文件构建嵌套树

如果已经生成了保存拆分记录的文件,可以通过映射+递归的方式构造树结构:

import ast

# 1. 读取文件构造父-子区间映射字典
parent_child_map = {}
# 替换为你的实际文件路径
with open("split_result.txt", "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        # 安全转换字符串格式的列表为Python对象
        item = ast.literal_eval(line)
        # 父区间转元组作为字典键(列表为可变类型不可作为键)
        parent = tuple(item[0])
        children = item[1]
        parent_child_map[parent] = children

# 2. 递归构造嵌套树
def build_tree_from_map(parent):
    parent_tuple = tuple(parent)
    # 无对应子节点直接返回当前区间
    if parent_tuple not in parent_child_map:
        return parent
    # 递归构造所有子节点的嵌套结构
    children = parent_child_map[parent_tuple]
    nested_children = [build_tree_from_map(child) for child in children]
    return [parent] + nested_children

# 传入顶层根节点生成最终树
root = [0, 250000000]
final_tree = build_tree_from_map(root)
print(final_tree)

两种方案最终输出的结构都符合要求:每个父节点下包含10个子节点,子节点如果可拆分则继续嵌套对应子结构,不可拆分则直接返回区间列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:51:02