Assume that we have n lists in python like A1,A2,...,An.
We name A*={x1,x2,...,xn}
a combination of these lists if x1
is in A1, x2 is in A2,..., xn
is in An
. By mathematics, we know that the number of these combinations is |A1| * |A2|*... * |An|
. How can I code a function in python to do this for me and return all these combinations?
Asked
Active
Viewed 46 times
1
-
1Is this what you were looking for: https://stackoverflow.com/questions/798854/all-combinations-of-a-list-of-lists – tanmay_garg May 21 '20 at 16:20
-
I am afraid this may be duplicate: [check here](https://stackoverflow.com/questions/798854/all-combinations-of-a-list-of-lists) – Hozayfa El Rifai May 21 '20 at 16:23
1 Answers
1
You can use itertools.product
:
from itertools import product
a1 = range(0, 3)
a2 = range(3, 6)
a3 = range(6, 9)
print(list(product(a1, a2, a3)))
Output:
[(0, 3, 6), (0, 3, 7), (0, 3, 8), (0, 4, 6), (0, 4, 7), (0, 4, 8), (0, 5, 6), (0, 5, 7), (0, 5, 8), (1, 3, 6), (1, 3, 7), (1, 3, 8), (1, 4, 6), (1, 4, 7), (1, 4, 8), (1, 5, 6), (1, 5, 7), (1, 5, 8), (2, 3, 6), (2, 3, 7), (2, 3, 8), (2, 4, 6), (2, 4, 7), (2, 4, 8), (2, 5, 6), (2, 5, 7), (2, 5, 8)]

iz_
- 15,923
- 3
- 25
- 40