Is there a better way to send multiple arguments to itertools.product?

Viewed 72

I am trying to create itertools.product from a 2D list containing many rows. For example, consider a list s:

[[0.7168573116730971,
  1.3404415914042531,
  1.8714268721791336,
  11.553051251803975],
 [0.6702207957021266,
  1.2476179147860895,
  1.7329576877705954,
  10.635778602978927],
 [0.6238089573930448,
  1.1553051251803976,
  1.5953667904468385,
  9.725277699842893],
 [0.5776525625901988,
  1.0635778602978927,
  1.4587916549764335,
  8.822689900641748]]

I want to compute itertools.product between the 4 rows of the list:

pr = []
for j in (it.product(s[0],s[1],s[2],s[3])):
    pr.append(j)

This gives the necessary result for pr which has dimensions 256,4 where 256 is (number of columns^number of rows). But, is there a better way to send all the rows of the list s as arguments without having to write each row's name. This would be annoying if it were to be done for a larger list.

I guess numpy.meshgrid can be used if s was a numpy.array. But even there, I'll have to jot down each row one by one as arguments.

1 Answers

You can use the unpacking notation * in Python for this:

import itertools as it

s = [[0.7168573116730971,
  1.3404415914042531,
  1.8714268721791336,
  11.553051251803975],
 [0.6702207957021266,
  1.2476179147860895,
  1.7329576877705954,
  10.635778602978927],
 [0.6238089573930448,
  1.1553051251803976,
  1.5953667904468385,
  9.725277699842893],
 [0.5776525625901988,
  1.0635778602978927,
  1.4587916549764335,
  8.822689900641748]]

pr = []
for j in (it.product(*s):
    pr.append(j)

It will send each item of your list s to the product function

Related