[英]count combinations in python
幾個小時我一直在困惑如何為這個問題制作一個程序。 我搜索了類似的解決方案,但我沒有成功。
共有6組2個值a [a1,a2] ; b [b1, b2] ; ... f [f1, f2].
a [a1,a2] ; b [b1, b2] ; ... f [f1, f2].
每個組合需要每組至少有一個值,但它也可以同時具有兩個值。 因此,有64種組合。
我需要的是計算所有這些組合,並打印這樣的東西:
Combination 1: a1, b1, c1, d1, e1, f1 Sum: (sum of those listed)
Combination 2: ...
Total sum:
>>> from itertools import product
>>> for item in product(['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']):
... print item
...
('a1', 'b1', 'c1')
('a1', 'b1', 'c2')
('a1', 'b2', 'c1')
('a1', 'b2', 'c2')
('a2', 'b1', 'c1')
('a2', 'b1', 'c2')
('a2', 'b2', 'c1')
('a2', 'b2', 'c2')
看起來你的a1,a2等是數字的。 那也沒關系
>>> from itertools import product
>>> for item in product([1, 2], [3, 4], [5, 6]):
... print item, sum(item)
...
(1, 3, 5) 9
(1, 3, 6) 10
(1, 4, 5) 10
(1, 4, 6) 11
(2, 3, 5) 10
(2, 3, 6) 11
(2, 4, 5) 11
(2, 4, 6) 12
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.