Combinations from list of lists
Question:
I want to get all the possible combinations like so:
a = [1, 2, 3]
b = [4, 5]
c = [-1]
print(list(product(a, b, c)))
Output:
[(1, 4, -1), (1, 5, -1), (2, 4, -1), (2, 5, -1), (3, 4, -1), (3, 5, -1)]
However, I have all my lists stored inside a list:
s = [[1,2,3], [4,5], [-1]]
print(list(product(s)))
Output:
[([1, 2, 3],), ([4, 5],), ([-1],)]
I’ve previously tried unpacking the list, but I’ve only been able to create one big list, or a dictionary. Is there another way of unpacking the list or getting the product in the same way as the first example?
Answers:
This is argument unpacking, demonstrated in the tutorial at 4.8.5. Unpacking Argument Lists:
>>> print(list(product(*s)))
[(1, 4, -1), (1, 5, -1), (2, 4, -1), (2, 5, -1), (3, 4, -1), (3, 5, -1)]
You can use *
from itertools import product
s = [[1,2,3], [4,5], [-1]]
result = list(product(*s))
print(result)
I want to get all the possible combinations like so:
a = [1, 2, 3]
b = [4, 5]
c = [-1]
print(list(product(a, b, c)))
Output:
[(1, 4, -1), (1, 5, -1), (2, 4, -1), (2, 5, -1), (3, 4, -1), (3, 5, -1)]
However, I have all my lists stored inside a list:
s = [[1,2,3], [4,5], [-1]]
print(list(product(s)))
Output:
[([1, 2, 3],), ([4, 5],), ([-1],)]
I’ve previously tried unpacking the list, but I’ve only been able to create one big list, or a dictionary. Is there another way of unpacking the list or getting the product in the same way as the first example?
This is argument unpacking, demonstrated in the tutorial at 4.8.5. Unpacking Argument Lists:
>>> print(list(product(*s)))
[(1, 4, -1), (1, 5, -1), (2, 4, -1), (2, 5, -1), (3, 4, -1), (3, 5, -1)]
You can use *
from itertools import product
s = [[1,2,3], [4,5], [-1]]
result = list(product(*s))
print(result)