Python:合并含列表的字典值并去重扁平化处理
Solution for Processing Nested List Dictionary
Got it, let's break down how to transform your training_data into the desired output. Here's a straightforward approach in Python:
Step-by-Step Explanation
We need to handle each value in the dictionary by:
- Flattening all nested sublists into a single list
- Removing duplicate elements (while preserving the order of first occurrence, matching your example)
- Collecting each processed list into the final result
Code Implementation
training_data = {1: [[1, 2], [1, 3], [1, 2, 5]], 2: [[1], [5], [1, 6]], 3: [[7], [5]]} result = [] for nested_groups in training_data.values(): # Flatten all sublists into one dimension flattened_items = [item for sublist in nested_groups for item in sublist] # Remove duplicates while keeping the order of first appearance unique_items = list(dict.fromkeys(flattened_items)) result.append(unique_items) print(result) # Output: [[1, 2, 3, 5], [1, 5, 6], [7, 5]]
Key Details
- Flattening: The double list comprehension
[item for sublist in nested_groups for item in sublist]iterates through every sublist in the group and extracts all its elements into a single list. For the first group, this turns[[1,2],[1,3],[1,2,5]]into[1,2,1,3,1,2,5]. - Order-Preserving Deduplication: Using
dict.fromkeys(flattened_items)creates a dictionary where keys are the elements from the flattened list (automatically removing duplicates) and preserves their insertion order (works in Python 3.7+). Converting this back to a list gives us the unique elements in the order they first appeared. - If Order Doesn't Matter: If you don't care about the order of elements, you can simplify the deduplication step to
list(set(flattened_items))—just note that sets are unordered, so the output list order might vary.
内容的提问来源于stack exchange,提问作者SXKDZ
相关产品推荐
相关产品推荐

