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

如何从多组不同元素集合中生成无重复的唯一组合

实现方案

首先明确需求的合法组合规则:每个有效组合固定为「A类1个元素 + B类1个元素 + C类1个元素」,总共有444=64种唯一合法组合,不会出现你举例里的A1B1BC1这类重复取同一类多个元素的错误结果。

通用思路

  • 遍历A列表的所有元素
  • 对每个A元素,遍历B列表的所有元素
  • 对每个(A,B)元素对,遍历C列表的所有元素
  • 拼接三个元素得到唯一组合,全部遍历完成后就能得到所有无重复的组合
  • 如果原始列表本身存在重复元素,可通过Set数据结构自动对最终结果去重

不同语言的实现示例

Python实现

你可以直接用内置的itertools.product方法快速生成三个列表的笛卡尔积,就是你要的所有唯一组合:

import itertools

A = ["A1", "A2", "A3", "A4"]
B = ["B1", "B2", "B3", "B4"]
C = ["C1", "C2", "C3", "C4"]

# 生成所有组合
combinations = [a + b + c for a, b, c in itertools.product(A, B, C)]

# 去重(原始列表无重复元素可省略这步)
unique_combinations = list(set(combinations))

不想依赖内置库也可以手写三层循环:

A = ["A1", "A2", "A3", "A4"]
B = ["B1", "B2", "B3", "B4"]
C = ["C1", "C2", "C3", "C4"]
combinations = []
for a in A:
    for b in B:
        for c in C:
            combinations.append(a + b + c)

JavaScript实现

const A = ["A1", "A2", "A3", "A4"]
const B = ["B1", "B2", "B3", "B4"]
const C = ["C1", "C2", "C3", "C4"]
const combinations = []
for (const a of A) {
    for (const b of B) {
        for (const c of C) {
            combinations.push(a + b + c)
        }
    }
}
// 去重可选
const uniqueCombinations = [...new Set(combinations)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:27:02