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

如何对嵌套列表全层级排序?及表格转缩进大纲技术问询

Hey there! Let's break down solutions for your two questions, starting with sorting nested lists across all levels, then moving on to converting that unique nested dictionary into an indented outline.


1. Sorting All Levels of a Nested List

Sorting nested lists recursively is all about handling each level and diving into sublists as you go. Here's a practical approach in Python:

Core Idea

  • Use a recursive function that first sorts any sublists within the current list.
  • Once all sublists are sorted, sort the current level itself.

Example Code

def sort_nested_list(nested_list):
    # Recursively sort any sublists first
    for index, item in enumerate(nested_list):
        if isinstance(item, list):
            sort_nested_list(nested_list[index])
    # Sort the current level of the list
    nested_list.sort()
    return nested_list

# Test with a sample nested list
sample = [5, [2, 7, [1, 3]], [4, 0]]
sorted_sample = sort_nested_list(sample)
print(sorted_sample)  # Output: [0, [2, [1, 3], 7], [4, 5]]

If your nested lists contain dictionaries (like your second question's data), adjust the sort to target a specific field (e.g., pos):

def sort_nested_dicts(nested_dict_list, sort_key="pos"):
    # Recursively sort child lists
    for item in nested_dict_list:
        for key, value in item.items():
            if isinstance(value, list):
                sort_nested_dicts(value, sort_key)
    # Sort current level by the specified key (convert to int for numeric order)
    nested_dict_list.sort(key=lambda x: int(x[sort_key]))
    return nested_dict_list

2. Converting Nested Dictionary to Indented Outline

Your dictionary structure uses IDs as keys, with each node containing name, pos, and nested child IDs. We'll split this into two steps: building a proper tree structure, then generating the indented outline.

Step 1: Build a Tree from the Dictionary

First, we'll map all nodes and identify root nodes (nodes not present as children in any other node):

def build_tree(d):
    node_map = {}
    root_nodes = []

    # Parse each node, separating children from core data
    for node_id, data in d.items():
        children = {}
        core_data = {}
        for key, value in data.items():
            if isinstance(key, int):  # Child entries are integer IDs
                children[key] = value
            else:  # Store fields like 'name' and 'pos'
                core_data[key] = value
        node_map[node_id] = {**core_data, "children": children, "id": node_id}

    # Find root nodes (not present as children in any other node)
    all_child_ids = set()
    for node in node_map.values():
        all_child_ids.update(node["children"].keys())
    root_nodes = [node_map[node_id] for node_id in node_map if node_id not in all_child_ids]

    return root_nodes, node_map

Step 2: Generate the Indented Outline

Next, we'll recursively traverse the tree, sort each level by pos, and build the outline text:

def generate_indented_outline(nodes, depth=0, indent="    "):
    outline = []
    # Sort current level nodes by numeric 'pos' value
    sorted_nodes = sorted(nodes, key=lambda x: int(x["pos"]))

    for node in sorted_nodes:
        # Add current node with appropriate indentation
        outline.append(f"{indent * depth}{node['name']}")
        # Recursively process child nodes
        child_nodes = [node_map[child_id] for child_id in node["children"]]
        outline.extend(generate_indented_outline(child_nodes, depth + 1, indent))
    
    return outline

# Test with your sample dictionary
d = {
    223: {'name':'fruit', 'pos':'1',
          634: {'name':'apple', 'pos':'1',
                945: {'name':'red','pos':'2'},
                306: {'name':'round','pos':'1'},
                847: {'name':'sweet','pos':'3'},
               },
          835: {'name':'banana', 'pos':'3'}
         }
}

root_nodes, node_map = build_tree(d)
outline_lines = generate_indented_outline(root_nodes)

# Print the final outline
for line in outline_lines:
    print(line)

Expected Output

fruit
    apple
        round
        red
        sweet
    banana

Key Notes

  • We convert pos to integers to ensure numeric sorting (so '10' comes after '2', not before).
  • The default indent is 4 spaces—swap the indent parameter to '\t' if you prefer tabs.
  • If there are multiple root nodes, they'll be sorted by pos and included at the top level.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:59:21