How to generate lists from a specification of element combinations

纵然是瞬间 提交于 2019-12-12 13:23:07

问题


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)

回答1:


You can create a double-for-loop list comprehension based on the solution you found:

>>> elements = [[10, 20], [30, 40], [50, 60]]
>>> [x for i in range(len(elements)) for 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 a bit cleaner, using enumerate:

>>> [x for i, _ in enumerate(elements) for x in itertools.product(*elements[:i+1])]


来源:https://stackoverflow.com/questions/35064310/how-to-generate-lists-from-a-specification-of-element-combinations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!