Question

I have a list of lists a= [ [1,2,3],[4,5,6,7],[8,9,10] ]

I want to get all possible combinations of length 2 among the lists ie

[ [1,4] ,[1,5], [1,6] , [1,7] , [1,8], [1,9] , [1,10] , [2,4], [2,5] etc etc ]

Was it helpful?

Solution

You can use itertools.combinations and itertools.product for this:

>>> from itertools import combinations, product, chain, starmap
>>> [p for c in combinations(a, 2) for p in product(*c)]
[(1, 4), (1, 5), (1, 6), (1, 7), (2, 4), (2, 5), (2, 6), (2, 7), (3, 4), (3, 5), (3, 6), (3, 7), (1, 8), (1, 9), (1, 10), (2, 8), (2, 9), (2, 10), (3, 8), (3, 9), (3, 10), (4, 8), (4, 9), (4, 10), (5, 8), (5, 9), (5, 10), (6, 8), (6, 9), (6, 10), (7, 8), (7, 9), (7, 10)]
#or list(chain(*starmap(product, combinations(a, 2))))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top