0

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!

1
  • I'd take a look at itertools Commented Oct 11, 2013 at 9:00

3 Answers 3

4

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

You beat me to it! =D
2

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)]

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.