I have two sets of options:
optionList1 = [a1,a2,a3,...,an]
optionList2 = [b1,b2,b3,...,bn]
The number of elements in the optionlists are not necessarily equal and I have to choose from the first optionlist twice. How do I ensure that I have tried every combination of 2 options from the first list and one from the second list. An example selection set below...
selectedOptions = [an1,an2,bn]
One way to do is to use itertools.product.
Assuming you don't want duplicate entries from list1, here's a generator that you can use to iterate over all combinations:
This, however, doesn't select the same options from list1 in different orderings. If you want to get both [a1, a2, b1] and [a2, a1, b1] then you can use:
It sounds to me like you're looking for
itertools.product()
Combine
product
andpermutations
fromitertools
assuming you don't want duplicates from the first list:You can use itertools.product for this. It returns all possible combinations.
For example
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*:
(*) This assumes that the options have some natural ordering which will be the case with all primitive values.
shang's answer is also very good. I wrote some code to compare them:
And the result is:
So the generator method is faster. However, speed is not everything. Personally I find my code 'cleaner', but the choice is yours!
(Btw, they give both identical counts, so both are equally correct.)