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

如何获取无重复嵌套列表的2至N元组合并实现去重合并?

Hey there! Let's walk through how to solve this problem exactly as you described. Here's a step-by-step solution with code examples:

Solution Breakdown

We'll use itertools.combinations to generate the required combinations, then leverage Python's built-in set data structure to automatically handle duplicates.

Step 1: Import Required Library

First, grab the itertools module for generating combinations, plus numpy if your input is a numpy array:

import itertools
import numpy as np  # Only needed if your input is a numpy array

Step 2: Prepare Your Input

Convert your numpy array to a standard Python list (skip this if your input is already a regular list):

# Your example input
a = np.array([[1,4,7],[8,2,5],[8,1,4,6],[8,1,3,5], [2,3,4,7],[2,5,6,7],[2,3,4,6,8],[1,3,5,6,7]])
input_list = a.tolist()

Step 3: Generate & Deduplicate Combinations

We'll use a set to store combinations (since sets automatically eliminate duplicates) and iterate through each sublist to generate all combinations of lengths 2 up to the sublist's maximum length:

unique_combinations = set()

for sublist in input_list:
    sublist_length = len(sublist)
    # Generate combinations for lengths 2 to the sublist's full length
    for combo_length in range(2, sublist_length + 1):
        # Create all combinations of the current length
        combos = itertools.combinations(sublist, combo_length)
        # Add each combo to the set (duplicates get ignored automatically)
        for combo in combos:
            unique_combinations.add(combo)

# Convert the set back to a list if you need a list output
result = list(unique_combinations)

Step 4: Check the Result

If you print result, you'll get all unique combinations from every sublist—covering lengths 2 up to each sublist's maximum length. For example, combinations like (1,4), (8,2,5), and (2,3,4,7) will all be included, with no duplicates even if they appeared in multiple sublists.

Key Notes:

  • Why a set? Combinations from itertools.combinations are tuples (hashable), so storing them in a set automatically removes any duplicate combinations across sublists.
  • Numpy array handling: Converting to a regular list simplifies working with itertools, since numpy arrays require extra steps to iterate through elements directly.
  • Customization: If you want combinations capped at a global length N (instead of each sublist's length), just replace sublist_length with your desired N—just make sure N doesn't exceed the length of any sublist you're processing (or add a quick check to avoid errors).

内容的提问来源于stack exchange,提问作者FeoJun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:25:03