python two dimensional recursion
<p>I have list pairs of keys and their possible values that are parsed from command line. eg:</p>

<p><code>[('-a',['1','2','3']), ('-b',['1','2'])]</code></p>

<p>my goal is to produce combinations as follows:</p>

<pre><code>prefix -a=1 -b=1 suffix
prefix -a=1 -b=2 suffix
prefix -a=2 -b=1 suffix
prefix -a=2 -b=2 suffix
prefix -a=3 -b=1 suffix
prefix -a=3 -b=2 suffix
</code></pre>

<p>problem is, the list can be of any length and so does the values in the sub lists.</p>

<p>The possible solution would be using some kind of recursion, so far what I wrote doesn't give me what I want:</p>

<pre><code>def runner(args, comd=""):
    for i in range(len(args)):
        op, vals = args[i]

        for val in vals:
            comd = op + "=" + val + " " + runner(args[1:], comd)

        if i == len(args) - 1:
            print ("prefix " + comd + " suffix")

    return comd
</code></pre>

<p>You want to do <a href="https://en.wikipedia.org/wiki/Cartesian_product" rel="nofollow">cartesian product</a> of two list. Use <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product()</code></a> for doing that. For example:</p>

<pre><code>&gt;&gt;&gt; my_list = [('-a',['1','2','3']), ('-b',['1','2'])]
&gt;&gt;&gt; from itertools import product
&gt;&gt;&gt; list(product(my_list[0][1], my_list[1][1]))
[('1', '1'), ('1', '2'), ('2', '1'), ('2', '2'), ('3', '1'), ('3', '2')]
</code></pre>

<p>It gives the <code>list</code> of all combinations of <code>tuple</code> from both list. </p>

<hr>

<p>Now, coming to your problem, below is the sample code:</p>

<pre><code>my_list = [('-a',['1','2','3']), ('-b',['1','2'])]
keys, value_list = zip(*my_list)
for item in product(*value_list):
    val_list = ['{}={}'.format(key, val) for key, val in zip(keys, item)]
    print 'prefix {} suffix'.format(' '.join(val_list))

# Output:
prefix -a=1 -b=1 suffix
prefix -a=1 -b=2 suffix
prefix -a=2 -b=1 suffix
prefix -a=2 -b=2 suffix
prefix -a=3 -b=1 suffix
prefix -a=3 -b=2 suffix
</code></pre>

<p><strong>Explanation:</strong></p>

<p><a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip([iterable, ...])</code></a> returns a <em>list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence</em>. For example, in above code:</p>

<pre><code>&gt;&gt;&gt; keys, value_list = zip(*my_list)  # zipping the unwrapped "my_list"
&gt;&gt;&gt; keys  # value of keys
('-a', '-b')
&gt;&gt;&gt; value_list  # value of values_list
(['1', '2', '3'], ['1', '2'])
</code></pre>

<p>Then I am doing the <em>cartesian product</em> on <code>values_list</code> (as explained in the very beginning) and again doing <code>zip</code> on the <code>keys</code> and each <code>item</code> of the cartesian product.</p>

python recursion combinations