英文:
Combinations from list of lists
问题
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?
英文:
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?
答案1
得分: 2
这是_参数解包_,在4.8.5. 解包参数列表教程中演示的:
>>> print(list(product(*s)))
[(1, 4, -1), (1, 5, -1), (2, 4, -1), (2, 5, -1), (3, 4, -1), (3, 5, -1)]
英文:
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)]
答案2
得分: 0
你可以使用 *
from itertools import product
s = [[1,2,3], [4,5], [-1]]
result = list(product(*s))
print(result)
英文:
You can use *
from itertools import product
s = [[1,2,3], [4,5], [-1]]
result = list(product(*s))
print(result)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论