random_forest
random_forest

Reputation: 47

Generating a 2-d array with iterations using Python

For example I have the following 2-d array

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

by using list comprehensions i get

>>> [[x, y, z] for x in t[2] for y in t[1] for z in t[0]]
[[6, 4, 1], 
 [6, 4, 2], 
 [6, 4, 3], 
 [6, 5, 1], 
 [6, 5, 2], 
 [6, 5, 3], 
 [7, 4, 1], 
 [7, 4, 2], 
 [7, 4, 3], 
 [7, 5, 1], 
 [7, 5, 2], 
 [7, 5, 3]]

But how if the inputs has more than 3 lists? I mean, I don't want hard codes the t[2], and something like that. I want to take t consisting any number of lists as input. Is there anyway using list comprehensions to do this?

Thanks in advance!

Upvotes: 0

Views: 69

Answers (3)

user27030
user27030

Reputation:

Have a look at the itertools module. The itertools.product function does what you want, except you may want to reverse the input order.

Upvotes: 0

Carsten
Carsten

Reputation: 18446

Use itertools.product:

In [1]: import itertools

In [2]: t = [[1,2,3], [4,5], [6,7]]

In [3]: list(itertools.product(*t[::-1]))
Out[3]:
[(6, 4, 1),
 (6, 4, 2),
 (6, 4, 3),
 (6, 5, 1),
 (6, 5, 2),
 (6, 5, 3),
 (7, 4, 1),
 (7, 4, 2),
 (7, 4, 3),
 (7, 5, 1),
 (7, 5, 2),
 (7, 5, 3)]

Upvotes: 2

falsetru
falsetru

Reputation: 369004

Use itertools.product:

>>> import itertools
>>> t = [[1,2,3], [4,5], [6,7]]
>>> [x for x in itertools.product(*t[::-1])]
[(6, 4, 1),
 (6, 4, 2),
 (6, 4, 3),
 (6, 5, 1),
 (6, 5, 2),
 (6, 5, 3),
 (7, 4, 1),
 (7, 4, 2),
 (7, 4, 3),
 (7, 5, 1),
 (7, 5, 2),
 (7, 5, 3)]
>>> [list(x) for x in itertools.product(*t[::-1])]
[[6, 4, 1],
 [6, 4, 2],
 [6, 4, 3],
 [6, 5, 1],
 [6, 5, 2],
 [6, 5, 3],
 [7, 4, 1],
 [7, 4, 2],
 [7, 4, 3],
 [7, 5, 1],
 [7, 5, 2],
 [7, 5, 3]]

Upvotes: 4

Related Questions