Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use <a href="http://docs.python.org/library/itertools.html#itertools.product" rel="nofollow noreferrer">itertools.product</a> for this. It returns all possible combinations.</p> <p>For example</p> <pre><code>for a1, a2, b in itertools.product(optionlist1,optionlist1,optionlist2): do_something(a1,a2,b) </code></pre> <p>This will produce "doubles" as [a1,a1,b2] and [a2,a3,b2],[a3,a2,b2]. You can fix this with a filter. The following prevents any doubles*: </p> <pre><code>for a1,a2,b in itertools.ifilter(lambda x: x[0]&lt;x[1], itertools.product(optionlist1,optionlist1,optionlist2)): do_something(a1,a2,b) </code></pre> <p>(*) This assumes that the options have some natural ordering which will be the case with all primitive values.</p> <p><a href="https://stackoverflow.com/users/572606/shang">shang</a>'s <a href="https://stackoverflow.com/questions/4906041/testing-all-combinations-in-python/4906054#4906054">answer</a> is also very good. I wrote some code to compare them: </p> <pre><code>from itertools import ifilter, product import random from timeit import repeat def generator_way(list1, list2): def combinations(list1, list2): return ([opt1, opt2, opt3] for i,opt1 in enumerate(list1) for opt2 in list1[i+1:] for opt3 in list2) count = 0 for a1,a2,b in combinations(list1,list2): count += 1 return count def itertools_way(list1,list2): count = 0 for a1,a2,b in ifilter(lambda x: x[0] &lt; x[1], product(list1,list1,list2)): count += 1 return count list1 = range(0,100) random.shuffle(list1) list2 = range(0,100) random.shuffle(list2) print sum(repeat(lambda: generator_way(list1,list2),repeat = 10, number=1))/10 print sum(repeat(lambda: itertools_way(list1,list2),repeat = 10, number=1))/10 </code></pre> <p>And the result is: </p> <pre><code>0.189330005646 0.428138256073 </code></pre> <p>So the generator method is faster. However, speed is not everything. Personally I find my code 'cleaner', but the choice is yours!</p> <p>(Btw, they give both identical counts, so both are equally correct.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload