嵌套列表转换问题:合并含空元素列表生成目标输出结构
Fixing Nested List Merging in Python
Let's walk through why your current code isn't producing the desired output, then build a working solution step by step.
Your Problem Recap
You have this input list:
original_list = [['a','b','c',''],['c','e','f'],['c','g','h']]
And you want to merge it into:
[['a','b','c','e','f'],['a','b','c','g','h']]
The rule: when a sublist ends with an empty string '', use its non-empty prefix as a base, then merge it with all sublists that start with the last element of that base.
What's Wrong With Your Current Code
Your approach has a few key issues:
- You're modifying the original list's elements directly instead of creating new, clean result lists
- You don't remove the trailing empty string from the "base" sublist
- The
combinefunction'sif not m in xcheck skips elements unnecessarily (we know we only need to avoid the duplicate starting element of the secondary lists) - There's no logic to collect and return the final merged lists as a proper result
Working Solution
Here's a function that implements your desired behavior clearly:
def merge_nested_lists(mylist): # Step 1: Find the base template (sublist ending with empty string) base_template = None for sublist in mylist: # Check if the sublist isn't empty and ends with '' if sublist and sublist[-1] == '': # Extract the non-empty part as our base base_template = sublist[:-1] break # If no template found, return original list if not base_template: return mylist.copy() # Step 2: Merge base with matching sublists merged_result = [] for sublist in mylist: # Skip the original template sublist, and check if sublist starts with base's last element if sublist != base_template + [''] and sublist[0] == base_template[-1]: # Merge base with sublist (skip the duplicate first element of sublist) merged = base_template + sublist[1:] merged_result.append(merged) return merged_result # Test it out original_list = [['a','b','c',''],['c','e','f'],['c','g','h']] print(merge_nested_lists(original_list)) # Output: [['a', 'b', 'c', 'e', 'f'], ['a', 'b', 'c', 'g', 'h']]
How This Works
- Find the Base Template: We loop through the input list to find the sublist ending with
'', then strip that empty string to get our base (['a','b','c']). - Merge Matching Sublists: We iterate through the input again, looking for sublists that start with the last element of our base (
'c'). For each match, we merge the base with the sublist (skipping the duplicate starting'c'to avoid redundancy). - Return Clean Result: We collect all merged lists and return them as the final output.
Edge Case Handling
- If no sublist ends with
'', the function returns a copy of the original list to avoid modifying the input. - It skips the original template sublist to prevent including it in the result.
内容的提问来源于stack exchange,提问作者baha joher
相关产品推荐
相关产品推荐

