如何基于列表首元素确定父子关系并转换指定二维列表结构
Hey there! Let's tackle your problem step by step. First, I'll break down the pattern from your input/output example, then show you how to implement the transformation, and finally explain the parent-child relationship logic behind it.
Step 1: Understand the Pattern
Looking at your input and desired output, here's the key rule we can spot:
- Nodes at level 1 (first element is
1) have no parent, so we addNoneas the second element. - Nodes at level
n(wheren > 1) take the last identifier (second element) of the most recent node from leveln-1as their parent ID. - Even when we drop back to a lower level (like going from level 3 back to 2), we still use the last recorded identifier from its direct parent level (level 1 in this case).
Step 2: Implement the Transformation (Python Example)
We can use a dictionary to track the last identifier for each level as we iterate through the list. Here's the code:
# Your original input list input_list = [ [1, '025', ...], [1, '026', ...], [2, '027', ...], [2, '028', ...], [3, '029', ...], [3, '030', ...], [2, '031', ...], [2, '032', ...], ] # Dictionary to keep track of the last identifier for each level level_last_identifier = {} output_list = [] for item in input_list: current_level = item[0] # Determine parent ID based on current level if current_level == 1: parent_id = None else: parent_level = current_level - 1 parent_id = level_last_identifier.get(parent_level) # Update the last identifier for the current level level_last_identifier[current_level] = item[1] # Build the new item with parent ID inserted new_item = [current_level, parent_id] + item[1:] output_list.append(new_item) # The output_list now matches your desired result print(output_list)
Step 3: How to Determine Parent-Child Relationships
From your example, the parent-child relationship is defined by two core rules:
- Hierarchical Level Adjacency: A node at level
nis a child of nodes in leveln-1. There's no cross-level parenting (e.g., level 3 nodes don't directly link to level 1 nodes). - Most Recent Parent Node: Instead of linking to every node in the parent level, each child node uses the last (most recent) node from the parent level as its parent. This is why all level 2 nodes use
'026'(the last level 1 node's identifier) as their parent, and all level 3 nodes use'028'(the last level 2 node's identifier) as their parent.
If your parent-child logic follows different rules (e.g., each node links to the previous node in the same level, or specific nodes map to specific parents), you can adjust the dictionary tracking or add additional lookup logic to fit those rules.
内容的提问来源于stack exchange,提问作者dimsdewn

