user4169482
user4169482

Reputation:

python itertools.product giving result wrongly as [(['x'],), ([0, 1],), ([0, 1, 2],)]

I have a list

e = [['x'], [0, 1], [0, 1, 2]] 

From this list, I would like to produce below output.

[('x', 0, 0), ('x', 0, 1), ('x', 1, 0), ('x', 1, 1), ('x', 2, 0), ('x', 2,1)]

Below is the code I used

import itertools
f=[[0], [2], [3]]
e=[['x']if f[j][0]==0 else range(f[j][0]) for j in range(len(f))]
print(e)
List1_=[]
for i in itertools.product(e):
  List1_.append(i)
print(List1_)

but I am getting output as

[(['x'],), ([0, 1],), ([0, 1, 2],)]

thanks, Sans

Upvotes: 2

Views: 73

Answers (2)

Iron Fist
Iron Fist

Reputation: 10951

You were not unpacking e in your code:

>>> list(product(e))
[(['x'],), ([0, 1],), ([0, 1, 2],)]
>>> 
>>> list(product(*e))
[('x', 0, 0), ('x', 0, 1), ('x', 0, 2), ('x', 1, 0), ('x', 1, 1), ('x', 1, 2)]
>>>

Quoting from Python Docs:

itertools.product(*iterables, repeat=1) Cartesian product of input iterables.

Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

If order matters to you than, just re-order your e list as :

>>> e = [['x'], [0, 1, 2], [0, 1]]  

Then you can get your expected output:

>>> list(product(*e))
[('x', 0, 0), ('x', 0, 1), ('x', 1, 0), ('x', 1, 1), ('x', 2, 0), ('x', 2, 1)]

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107297

That's what that itertools.product is for. But you need to change the second and 3rd item in order to create the expected product.

Also note that you need to use * operand for unpacking your nested list. Because product accepts multiple iterable and calculates the product of them. Thus you need to pass your sub lists instead of the whole of your list.

>>> e = [['x'], [0, 1, 2], [0, 1]]   
>>> list(product(*e))
[('x', 0, 0), ('x', 0, 1), ('x', 1, 0), ('x', 1, 1), ('x', 2, 0), ('x', 2, 1)]

Upvotes: 2

Related Questions