How can I make all possible pairs between arrays?

Question:

Let’s say I have the following list:

lst = [[1,2],[3,4,],[5,6]]

There are only three lists within this list, but there could be more. I want to write a script that will give me the following combinations:

[[1,3],[1,4],[1,5],[1,6],[2,3],[2,4],[2,5],[2,6],[3,5],[3,6],[4,5],[4,6]]

The order does not necessarily need to be the same. Notice that no pairs are generated between elements in the same original array. What I came up with is the following:

import itertools
import numpy as np

sets = []
lst = [[1,2],[3,4,],[5,6]]
count = 0
for i in range(len(lst)-1):
    for i, j in itertools.product(lst[count], list(np.array(lst[count+1:]).flatten())):
        sets += [[i,j]]
    count += 1

I believe this code works because I get the following result:

[[1, 3], [1, 4], [1, 5], [1, 6], [2, 3], [2, 4], [2, 5], [2, 6], [3, 5], [3, 6], [4, 5], [4, 6]]

Is there a cleaner way to do this, though? I feel like there’s some simple itertools function that could do this in like two lines that I’m missing.

Asked By: arara

||

Answers:

You can use itertools.combinations

[[x, y] for (xs, ys) in combinations(lst, 2) for x in xs for y in ys]

Or you can achieve same thing only using list comprehensions

[
    [x, y]
    for (i, xs) in enumerate(lst)
    for (j, ys) in enumerate(lst)
    if i < j
    for x in xs
    for y in ys
]
Answered By: ekim boran
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.