Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply itertools.product to elements of a list of lists?

I have a list of arrays and I would like to get the cartesian product of the elements in the arrays.

I will use an example to make this more concrete...

itertools.product seems to do the trick but I am stuck in a little detail.

arrays = [(-1,+1), (-2,+2), (-3,+3)]; 

If I do

cp = list(itertools.product(arrays)); 

I get

cp = cp0 = [((-1, 1),), ((-2, 2),), ((-3, 3),)] 

But what I want to get is

cp1 = [(-1,-2,-3), (-1,-2,+3), (-1,+2,-3), (-1,+2,+3), ..., (+1,+2,-3), (+1,+2,+3)]. 

I have tried a few different things:

cp = list(itertools.product(itertools.islice(arrays, len(arrays)))); cp = list(itertools.product(iter(arrays, len(arrays)))); 

They all gave me cp0 instead of cp1.

Any ideas?

Thanks in advance.

like image 641
W7GVR Avatar asked Jun 13 '10 21:06

W7GVR


People also ask

Is Itertools product faster than for loops?

That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.

How do you code a cartesian product in Python?

Get Cartesian Product in Python Using the itertools ModuleThe product(*iterables, repeat=1) method of the itertools module takes iterables as input and returns their cartesian product as output. The cartesian product order will be the order of each set/list in the provided argument iterables .


2 Answers

>>> list(itertools.product(*arrays)) [(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)] 

This will feed all the pairs as separate arguments to product, which will then give you the cartesian product of them.

The reason your version isn't working is that you are giving product only one argument. Asking for a cartesian product of one list is a trivial case, and returns a list containing only one element (the list given as argument).

like image 126
interjay Avatar answered Oct 07 '22 15:10

interjay


>>> arrays = [(-1,+1), (-2,+2), (-3,+3)] >>> list(itertools.product(*arrays)) [(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)] 
like image 25
rkhayrov Avatar answered Oct 07 '22 15:10

rkhayrov