python - How to generate lists from a specification of element combinations -
i want generate bunch of lists using combinations of elements specified in form following:
[[10, 20], [30, 40], [50, 60]]
this means values available first element 10 , 20, values available second element 30 , 40 , on (i've used 2 element options each element brevity; there more that). want use specification generate lists using combinations of these elements (including possibility of not having any), generating 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 though itertools
used this, i'm not sure how implement algorithm generate lists this. good, general way (i.e. not limited 3 elements 3 hardcoded nested loops, instance) generate lists specification i've shown above?
as attempt, i've got following:
import itertools element_specifications = [[10, 20], [30, 40], [50, 60]] lists = [list(list_configuration) list_configuration in list(itertools.product(*element_specifications))] list_configuration in lists: print(list_configuration)
this produces following lists, note misses out on possibilities arise 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 following, seems inelegant me:
import itertools element_specifications = [[10, 20], [30, 40], [50, 60]] lists = [] length in range(1, len(element_specifications) + 1): lists.extend([list(list_configuration) list_configuration in list(itertools.product(*element_specifications[:length]))]) list_configuration in lists: print(list_configuration)
you can create double-for-loop list comprehension based on solution found:
>>> elements = [[10, 20], [30, 40], [50, 60]] >>> [x in range(len(elements)) x in itertools.product(*elements[:i+1])] [(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)]
or maybe bit cleaner, using enumerate
:
>>> [x i, _ in enumerate(elements) x in itertools.product(*elements[:i+1])]
Comments
Post a Comment