0

I would like to generate a Cartesian product of N variables, N being itself a variable. Let table be a list, how can I get the cartesian product of [0, table[i] - 1] for all i?
If I knew that table's length is always 3, I would write itertools.product(xrange(table[0]), xrange(table[1]), xrange(table[2])). But how to do that with an undefined table length?
Thanks for any help.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Yuufo
  • 11
  • 1
  • 3

2 Answers2

4

You want to use Python's "splat" operator func(*iterable).

>>> import itertools
>>> table = [1, 5, 3]
>>> iterator = itertools.product(*map(xrange, table))
>>> list(iterator)
[(0, 0, 0), (0, 0, 1), (0, 0, 2),
(0, 1, 0), (0, 1, 1), (0, 1, 2),
(0, 2, 0), (0, 2, 1), (0, 2, 2),
(0, 3, 0), (0, 3, 1), (0, 3, 2),
(0, 4, 0), (0, 4, 1), (0, 4, 2)]
Alyssa Haroldsen
  • 3,652
  • 1
  • 20
  • 35
2

One way would be using list comprehensions:

itertools.product(*[xrange(t) for t in table])
KurzedMetal
  • 12,540
  • 6
  • 39
  • 65