如何用Python构建多层级分类树结构并遍历至末层随机选节点
Alright, let's break this down properly. First, since nested lists won't cut it for representing hierarchical categories with clear parent-child relationships, we'll use a nested dictionary structure where each node has a name (the category label) and a children list (containing its sub-category nodes). This structure is intuitive, easy to traverse, and scales well for future CSV imports.
Step 1: Manually Build the Hierarchical Structure
Here's how to represent your given categories with this structure:
# Manual hierarchical category structure categories = [ { "name": "A", "children": [ { "name": "A1", "children": [ {"name": "A11", "children": []}, { "name": "A12", "children": [ {"name": "A121", "children": []}, {"name": "A122", "children": []} ] } ] }, {"name": "A2", "children": []} ] }, {"name": "B", "children": []}, { "name": "C", "children": [ {"name": "C1", "children": []}, {"name": "C2", "children": []} ] } ]
Step 2: Traverse to Deepest Levels & Randomly Select a Category
We'll use a recursive function to collect all "leaf nodes" (deepest-level categories with no children), then randomly pick one from each top-level category's leaf set.
import random def get_leaf_nodes(node, leaves=None): """Recursively collect all leaf nodes (deepest categories) from a given node""" if leaves is None: leaves = [] # If the node has no children, it's a leaf if not node["children"]: leaves.append(node["name"]) else: # Recurse through all child nodes for child in node["children"]: get_leaf_nodes(child, leaves) return leaves # Iterate through each top-level category and select a random leaf for top_cat in categories: top_name = top_cat["name"] leaf_nodes = get_leaf_nodes(top_cat) selected_leaf = random.choice(leaf_nodes) print(f"Top category *{top_name}*: Randomly selected deepest category → {selected_leaf}")
Example Output
Top category *A*: Randomly selected deepest category → A121 Top category *B*: Randomly selected deepest category → B Top category *C*: Randomly selected deepest category → C2
Step 3: Future Plan - Import from CSV
For CSV imports, structure your CSV with each row representing a full path to a leaf category (e.g., A,A1,A12,A121). Here's a function to convert this CSV into our nested dictionary structure:
import csv def build_categories_from_csv(csv_file_path): """Build the hierarchical category structure from a CSV file""" categories = [] node_map = {} # Tracks nodes by their full path to avoid duplicates with open(csv_file_path, newline='', encoding='utf-8') as csvfile: reader = csv.reader(csvfile) for row in reader: current_parent = None for idx, cat_name in enumerate(row): # Create a unique key for the node using its full path node_key = ">".join(row[:idx+1]) if node_key not in node_map: new_node = {"name": cat_name, "children": []} node_map[node_key] = new_node # Add to top-level list if it's a root category if current_parent is None: categories.append(new_node) # Add to parent's children if it's a sub-category else: current_parent["children"].append(new_node) current_parent = node_map[node_key] return categories # Usage example: # categories = build_categories_from_csv("categories.csv")
Your CSV file (categories.csv) would look like this:
A,A1,A11 A,A1,A12,A121 A,A1,A12,A122 A,A2 B C,C1 C,C2
内容的提问来源于stack exchange,提问作者user3541631

