I want to generate a bunch of lists using combinations of elements specified in a form like the following:
[[10, 20], [30, 40], [50, 60]]
This means that the values available for the first element are 10 and 20, the values available for the second element are 30 and 40 and so on (I've used just two element options for each element for brevity; there could be more than that). I want to use this specification to generate all lists using the combinations of these elements (including the possibility of not having any), generating something like the following:
[10]
[20]
[10, 30]
[10, 40]
[20, 30]
[20, 40]
[10, 30, 50]
[10, 30, 60]
[10, 40, 50]
[10, 40, 60]
[20, 30, 50]
[20, 30, 60]
[20, 40, 50]
[20, 40, 60]
I feel as though itertools
could be used for this, but I'm not sure how to implement an algorithm to generate lists like this. What would be a good, general way (i.e. not limited to three elements by three hardcoded nested loops, for instance) to generate lists from a specification like that which I've shown above?
As an attempt, I've got the following:
import itertools
element_specifications = [[10, 20], [30, 40], [50, 60]]
lists = [list(list_configuration) for list_configuration in list(itertools.product(*element_specifications))]
for list_configuration in lists:
print(list_configuration)
This produces the following lists, but note that it misses out on the possibilities that arise from having no element:
[10, 30, 50]
[10, 30, 60]
[10, 40, 50]
[10, 40, 60]
[20, 30, 50]
[20, 30, 60]
[20, 40, 50]
[20, 40, 60]
EDIT: I've come up with the following, but it seems very inelegant to me:
import itertools
element_specifications = [[10, 20], [30, 40], [50, 60]]
lists = []
for length in range(1, len(element_specifications) + 1):
lists.extend([list(list_configuration) for list_configuration in list(itertools.product(*element_specifications[:length]))])
for list_configuration in lists:
print(list_configuration)