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

如何用Python生成忽略顺序重复的列表元素全长度排列

无重复全长度组合生成方案

你需要的是不考虑元素顺序的全长度非空组合,itertools.permutations生成的是排列(顺序不同算不同结果),显然不符合需求,用itertools.combinations就能高效解决问题——它专门用于生成无顺序重复的组合。

实现代码

import itertools

model = ["AT", "V", "AP", "RH"]
all_combinations = []

# 遍历1到列表长度的所有组合长度
for combo_length in range(1, len(model) + 1):
    # 生成对应长度的所有组合,转成列表存入结果
    combo_list = [list(combo) for combo in itertools.combinations(model, combo_length)]
    all_combinations.extend(combo_list)

# 输出结果示例
for combo in all_combinations:
    print(combo)

关键说明

  • itertools.combinations(model, r):生成列表中所有长度为r的组合,元素顺序不影响,不会出现["AT","V"]和["V","AT"]这类重复项
  • 循环覆盖1到len(model)的所有长度,确保包含单个元素、多元素直到全元素的所有组合
  • 标准库实现经过优化,比手动编写组合逻辑更高效、更可靠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 13:45:24