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

如何获取含重复元素列表的无重复全排列生成器

带重复元素的无重复全排列生成器实现

itertools.product本质是求多组元素的笛卡尔积,允许元素重复选取,因此会出现和原列表元素计数不符的结果,不符合排列的要求。以下是两种符合需求的生成器实现:

方案1:标准库快速实现(适合小数据量)

基于itertools.permutations生成全排列后做实时去重,代码简洁:

from itertools import permutations

def unique_permutations(lst):
    visited = set()
    for perm in permutations(lst):
        if perm not in visited:
            visited.add(perm)
            yield perm

调用示例:list(unique_permutations([2,2,1])) 输出为 [(2, 2, 1), (2, 1, 2), (1, 2, 2)]

方案2:回溯生成器(高效无冗余,适合大数据量)

生成过程中直接跳过重复选择,不会产生多余的重复排列,全程流式输出无额外内存占用:

from collections import Counter

def unique_permutations(lst):
    num_count = Counter(lst)
    total_len = len(lst)

    def backtrack(current_path):
        if len(current_path) == total_len:
            yield tuple(current_path)
            return
        for num in num_count:
            if num_count[num] == 0:
                continue
            num_count[num] -= 1
            current_path.append(num)
            yield from backtrack(current_path)
            current_path.pop()
            num_count[num] += 1

    yield from backtrack([])

两种实现都返回生成器对象,遍历即可得到所有不重复的排列结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 14:24:05