Luis
Luis

Reputation: 185

how to get a list of the possible pairs in a list of lists - python

I have the following list of lists

a = [[1,2,3],[4,5,6,7]]

trying to get the following result

b = [[1,2],[1,3],[2,3],[4,5],[4,6],[4,7],[5,6],[5,7],[6,7]]

I have tried to use

b = list(itertools.product(a))

but I got a combination of the first with the second. Appreciate any help thanks

Upvotes: 1

Views: 180

Answers (1)

cs95
cs95

Reputation: 402593

If you are looking for a solution using the standard library, this uses a list comprehension to call itertools.combinations on each sublist.

from itertools import combinations
b = [list(c) for l in a for c in combinations(l, r=2)]
b
# [[1, 2], [1, 3], [2, 3], [4, 5], [4, 6], [4, 7], [5, 6], [5, 7], [6, 7]]

Another very functional way of computing this is using map; this returns a list of tuples.

from itertools import chain, combinations
from functools import partial

fn = partial(combinations, r=2)
b = list(chain.from_iterable(map(fn, a))) 
b 
# [(1, 2), (1, 3), (2, 3), (4, 5), (4, 6), (4, 7), (5, 6), (5, 7), (6, 7)]

Upvotes: 3

Related Questions