Reputation: 1373
I have three lists (L1, L2, L3), something like :
L1 = [1,2]
L2 = ['a','b']
L3 = ['A','B']
I want to compute the product of L1*L2*L3, id est,
itertools.product(L1,L2,L3) = [ [1,'a','A'], [1,'a','B'], ... ]
but I want to take or not in account some lists; hence,[1,], [ 1, 'a' ] would be a part of the result, like ['a',], ['a', 'B'] and so on.
Any idea to help me ? Thanks !
Upvotes: 0
Views: 63
Reputation: 110069
Use the powerset
function given in the itertools examples. powerset([L1,L2,L3])
will give you all subsets of the set of 3 lists. For each subset you can take the cartesian product, and then chain them all together.
>>> from itertools import chain, product
>>> result = chain.from_iterable(product(*lists) for lists in powerset([L1,L2,L3]))
>>> list(result)
[(), (1,), (2,), ('a',), ('b',), ('A',), ('B',), (1, 'a'), (1, 'b'), (2, 'a'),
(2, 'b'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B'), ('a', 'A'), ('a', 'B'),
('b', 'A'), ('b', 'B'), (1, 'a', 'A'), (1, 'a', 'B'), (1, 'b', 'A'),
(1, 'b', 'B'), (2, 'a', 'A'), (2, 'a', 'B'), (2, 'b', 'A'), (2, 'b', 'B')]
Upvotes: 3