首页 > 解决方案 > 如何仅过滤排列中的唯一对,python?

问题描述

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

输出:

1 2
1 3
2 1
2 3
3 1
3 2

此输出包含所有可能的排列,我需要唯一的数字组合,我应该如何过滤它们,也许我应该使用另一个代码。我需要

1 2
1 3
2 3

标签: pythonalgorithmloops

解决方案


您可以使用combinations而不是permutations来实现

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

推荐阅读