TMichel TMichel - 4 years ago 128
Python Question

Python: find all possible combinations between one array and N arrays

In Python, I am looking for a generic way (i.e. itertools) to build an

with all possible combinations between a given one dimensional array and N one dimensional arrays.

Here is a simplified example.


main = ["a1","a2","a3"]
secondary = [["b1","b2"],["c1","c2","c3"]]

Expected output


Answer Source

You can do it with itertools.product() like so:

from itertools import product

main = ["a1","a2","a3"]
secondary = [["b1","b2"],["c1","c2","c3"]]
[list(a) for a in product(main, *secondary)]


[['a1', 'b1', 'c1'],
 ['a1', 'b1', 'c2'],
 ['a1', 'b1', 'c3'],
 ['a1', 'b2', 'c1'],
 ['a1', 'b2', 'c2'],
 ['a1', 'b2', 'c3'],
 ['a2', 'b1', 'c1'],
 ['a2', 'b1', 'c2'],
 ['a2', 'b1', 'c3'],
 ['a2', 'b2', 'c1'],
 ['a2', 'b2', 'c2'],
 ['a2', 'b2', 'c3'],
 ['a3', 'b1', 'c1'],
 ['a3', 'b1', 'c2'],
 ['a3', 'b1', 'c3'],
 ['a3', 'b2', 'c1'],
 ['a3', 'b2', 'c2'],
 ['a3', 'b2', 'c3']]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download