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

Python如何从permutations排列结果中筛选唯一无序元素对

解决方案

方法1:使用原生无序组合生成函数(更推荐)

你需要的是不考虑顺序的元素组合,itertools模块已经提供了专门的combinations方法,原生就不会生成重复的无序对,效率比生成排列后过滤更高:

from itertools import combinations
list0 = [1, 2, 3]
for el1, el2 in combinations(list0, r=2):
    print(el1, el2)

运行后直接输出你需要的目标结果:

1 2
1 3
2 3

方法2:过滤现有排列结果

如果你已经基于permutations生成了全排列结果,只需要加个简单的大小判断,保留左小右大的数对即可去重:

from itertools import permutations
list0 = [1, 2, 3]
for el1, el2 in permutations(list0, r=2):
    # 每个无序数对仅有一种左小右大的形式,过滤后即可去重
    if el1 < el2:
        print(el1, el2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 17:24:03