组合来自列表的列表

huangapple go评论62阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年3月4日 01:31:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630186.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定