I've been reading about itertools
, which seems to be a very powerful module. I am particularly interested in itertools.product()
which appears to give me all of the combinations of the iterable inputs.
However, I would like to know which of the input iterables each of the outputs are coming from. For example, a simple standard example is:
itertools.product([1, 2, 3], [1, 2])
If the user provided the inputs of [1,2,3], [1, 2] I won't know which order they came in, so getting a result of
(1, 2)
isn't much help, as I don't know which way round they will be. Is there some way of providing input like:
itertools.product(foo = [1, 2, 3], bar = [1, 2])
and then getting outputs like:
output['foo'] = 1
output['bar'] = 2
or
output.foo = 1
output.bar = 2
The result will always be ordered according to the argument order of product, i.e. in
(1, 2)
the1
must come from[1,2,3]
and the2
must come from[1,2]
.Therefore, your requirement can be satisfied by reusing itertools.product:
The output of
itertools.product([1, 2, 3], [1, 2])
is a series of ordered pairs whether the first element comes from[1,2,3]
and the second element from[1,2]
. This is guaranteed behavior.If field names are desired, you can cast the result to a named tuple. As you requested, the named tuple lets you access the fields with
output.foo
andoutput.bar
. Incorporating KennyTM's idea of using**items
, it can be packaged in a single function that is fast and memory efficient:Here's an example call: