Get all pairwise combinations from a list

后端 未结 2 1014
刺人心
刺人心 2021-01-11 12:22

For example, if the input list is

[1, 2, 3, 4]

I want the output to be

[[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]]
2条回答
  •  温柔的废话
    2021-01-11 13:20

    Though the previous answer will give you all pairwise orderings, the example expected result seems to imply that you want all unordered pairs.

    This can be done with itertools.combinations:

    >>> import itertools
    >>> x = [1,2,3,4]
    >>> list(itertools.combinations(x, 2))
    [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
    

    Compare to the other result:

    >>> list(itertools.permutations(x, 2))
    [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
    

提交回复
热议问题