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

Python如何从含重复元素的列表中获取去重后的唯一组合

方案1:小数据量快速实现

如果原列表长度不大,直接对itertools.combinations返回的结果做去重即可,Python 3.7及以上版本可以用dict.fromkeys保留组合的生成顺序:

import itertools
L = [2,2,3]
res = list(dict.fromkeys(itertools.combinations(L, 2)))
print(res)  # 输出 [(2, 2), (2, 3)]

如果不要求保留组合的生成顺序,也可以直接转集合再转列表:list(set(itertools.combinations(L, 2)))。

方案2:大数据量高效实现

如果原列表长度大、重复元素多,先生成所有重复组合再去重会浪费性能,此时可以先统计每个元素的出现频次,再基于频次过滤合法组合,避免生成无效的冗余结果:

import itertools
from collections import Counter

def unique_combinations(lst, k):
    cnt = Counter(lst)
    # 基于去重后的元素生成带替换的组合候选
    for comb in itertools.combinations_with_replacement(cnt.keys(), k):
        # 校验当前组合的元素频次不超过原列表的实际频次
        comb_cnt = Counter(comb)
        if all(comb_cnt[num] <= cnt[num] for num in comb_cnt):
            yield comb

L = [2,2,3]
res = list(unique_combinations(L, 2))
print(res)  # 输出 [(2, 2), (2, 3)]

内容的提问来源于stack exchange,提问作者Erel Segal-Halevi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:06:06