Reputation: 681
My goal is to produce a list comprising all combination of elements from specified groups. The output should be a 2D list but I am unable to generate anything other than a 3D list. Can I generate the 2D list directly, or is it necessary to convert the 3D list to a 2D list? If so, how?
# elements comprising each of groups a1-a4
a1 = ['one','two','three']
a2 = ['four','five','six']
a3 = ['seven','eight','nine']
a4 = ['ten','eleven','twelve']
# each row in b specifies two or more groups, whereby all combinations of one
# element from each group is found
b = [[a1,a2],
[a3, a4]]
# map(list,...) converts tuples from itertools.product(*search) to lists
# list(map(list,...)) converts map object into list
# [...] performs list comprehension
l = [list(map(list, itertools.product(*search))) for search in b]
print(l)
Output: [[['one', 'four'], ..., ['nine', 'twelve']]]
Desired Output: [['one', 'four'], ..., ['nine', 'twelve']]
Upvotes: 0
Views: 78
Reputation: 8190
Obviously, you can create your list as follows:
l = []
for search in b:
l += list(map(list, itertools.product(*search)))
But if you want to stick with a list comprehension, you can do:
l = list(itertools.chain(*[map(list, itertools.product(*search)) for search in b]))
Or:
l = list(map(list, itertools.chain(*[itertools.product(*search) for search in b])))
It creates and chains the two cartesian products, and then maps the tuples to lists.
Upvotes: 1