You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:16:16