多级嵌套列表按层级从深到浅分组排序的实现需求问询
To solve this problem, we need to restructure a nested list such that the deepest sublists (with their non-sublist elements) appear first, followed by sublists from the next shallower level, and so on, ending with the top-level non-sublist elements. Here's a step-by-step approach and implementation in Python:
Approach
- Recursive Traversal: We traverse the nested list recursively, keeping track of the depth of each sublist.
- Group Collection: For each sublist (including the top-level list), we collect its non-sublist elements into a group associated with its depth.
- Sort by Depth: We then sort these groups in descending order of their depth, so deepest groups come first.
This approach handles any arbitrary nested structure and allows for flexible ordering of groups at the same depth (as per your requirement).
Implementation Code
from collections import defaultdict def restructure_nested_list(nested_list): depth_groups = defaultdict(list) max_depth = 0 def helper(current_list, current_depth): nonlocal max_depth # Collect non-list elements from the current sublist current_group = [] for item in current_list: if isinstance(item, list): # Recursively process deeper sublists helper(item, current_depth + 1) else: current_group.append(item) # Add the current group to its depth category (even if empty) depth_groups[current_depth].append(current_group) # Update the maximum depth encountered if current_depth > max_depth: max_depth = current_depth # Start processing from the top-level list (depth 0) helper(nested_list, 0) # Build the result by iterating from deepest to shallowest depth result = [] for depth in range(max_depth, -1, -1): result.extend(depth_groups[depth]) return result
Example Usage
Example 1
Input:
original = ['A', 'B', 'C', ['D', ['E', 'F'], 'G'], 'H'] print(restructure_nested_list(original))
Output:
[['E', 'F'], ['D', 'G'], ['A', 'B', 'C', 'H']]
Example 2
Input:
original = ['A', 'B', 'C', ['D', ['E', 'F'], 'G'], ['H', 'I', 'J']] print(restructure_nested_list(original))
Possible Output (order of same-depth groups may vary):
[['E', 'F'], ['D', 'G'], ['H', 'I', 'J'], ['A', 'B', 'C']]
Edge Case: Empty Sublists
Input:
original = [1, [2, [3], 4], [5, []]] print(restructure_nested_list(original))
Possible Output:
[['3'], [], ['2', '4'], ['5'], ['1']]
How It Works
- Recursive Helper Function: The
helperfunction processes each sublist at the given depth. For every item in the sublist:- If it's another list, we recursively process it at the next depth level.
- If it's a non-list element, we add it to the current group for the current depth.
- Group Storage: Groups are stored in a dictionary where keys are depth levels and values are lists of groups at that depth.
- Result Construction: We iterate from the deepest depth down to 0, adding all groups at each depth to the result list. This ensures deepest groups come first.
This approach efficiently handles any nested list structure and adheres to your requirement of ordering by depth from deepest to shallowest.
内容的提问来源于stack exchange,提问作者mimookies

