![](/img/trans.png)
[英]How to find all combinations of picking one item from the first list and at most n items from the second list
[英]Get all possible combinations from a list of lists by picking one item from each list
我有一個列表列表,我想通過從每個列表中選擇一個項目來獲得所有可能的組合。
例如以下列表:
l = [[1,2],[3],[4,5,6],[7],[8,9]]
output 應該是:
1,3,4,7,8
1,3,5,7,8
1,3,6,7,8
1,3,4,7,9
1,3,5,7,9
1,3,6,7,9
2,3,4,7,8
2,3,5,7,8
2,3,6,7,8
2,3,4,7,9
2,3,5,7,9
2,3,6,7,9
列表及其項目的數量是隨機的
>>> l = [[1,2],[3],[4,5,6],[7],[8,9]]
>>> from itertools import product
>>> list(product(*l))
[(1, 3, 4, 7, 8), (1, 3, 4, 7, 9), (1, 3, 5, 7, 8), (1, 3, 5, 7, 9), (1, 3, 6, 7, 8), (1, 3, 6, 7, 9), (2, 3, 4, 7, 8), (2, 3, 4, 7, 9), (2, 3, 5, 7, 8), (2, 3, 5, 7, 9), (2, 3, 6, 7, 8), (2, 3, 6, 7, 9)]
itertools為您完成工作
In [1]: from itertools import product
In [2]: l = [[1,2],[3],[4,5,6],[7],[8,9]]
In [3]: product(*l)
Out[3]: <itertools.product at 0x7f012ba3e780>
In [4]: list(product(*l))
Out[4]:
[(1, 3, 4, 7, 8),
(1, 3, 4, 7, 9),
(1, 3, 5, 7, 8),
(1, 3, 5, 7, 9),
(1, 3, 6, 7, 8),
(1, 3, 6, 7, 9),
(2, 3, 4, 7, 8),
(2, 3, 4, 7, 9),
(2, 3, 5, 7, 8),
(2, 3, 5, 7, 9),
(2, 3, 6, 7, 8),
(2, 3, 6, 7, 9)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.