python-3.xarraylistcombinationsmethod-combination

How could I generate a combinatorial of the lines of an array with several columns?


I want to get all possible combinations of n lines of an array. I don't care what order they are, so it's not a permutacion.

Example:

I have an array:

[(1,2,3), (4,5,6), (7,8,9)]

Question: I want to find all combinations of two lines:

[(1,2,3), (4,5,6)]
[(1,2,3), (7,8,9)]
…

Thank you so much!!


Solution

  • Use itertools.combinations and cast the combinations to a list, see the docs:

    from itertools import combinations
    
    lst = [(1,2,3), (4,5,6), (7,8,9)]
    for x in combinations(lst, 2):
        print(list(x))