Generate All Possible Lists From The Sublist In Python
Suppose I have list [['a', 'b', 'c'], ['d', 'e'], ['1', '2']] I want to generate list where on the first place is any value from first sublist, on the second - from second etc. So,
Solution 1:
You need itertools.product()
which return cartesian product of inpur iterables:
>>> from itertools import product
>>> my_list = [['a', 'b', 'c'], ['d', 'e'], ['1', '2']]
# v Unwraps the list
>>> list(product(*my_list))
[('a', 'd', '1'),
('a', 'd', '2'),
('a', 'e', '1'),
('a', 'e', '2'),
('b', 'd', '1'),
('b', 'd', '2'),
('b', 'e', '1'),
('b', 'e', '2'),
('c', 'd', '1'),
('c', 'd', '2'),
('c', 'e', '1'),
('c', 'e', '2')]
Post a Comment for "Generate All Possible Lists From The Sublist In Python"