我使用这段代码从一组给定的列表中生成三个数字的组合。
import itertools
thelist = [0, 0, 0, 1, 1, 2, 2, 1]
for L in range(3,4):
for subset in itertools.combinations(thelist, L):
print(subset)
哪个工作正常,结果如下:
(0, 0, 0)
(0, 0, 1)
(0, 0, 1)
(0, 0, 2)
(0, 0, 2)
(0, 0, 1)
(0, 0, 1)
(0, 0, 1)
(0, 0, 2)
(0, 0, 2)
(0, 0, 1)
(0, 1, 1)
(0, 1, 2)
(0, 1, 2)
(0, 1, 1)
(0, 1, 2)
(0, 1, 2)
(0, 1, 1)
我想列出产生的组合的总和。我怎样才能做到这一点? 这样输出将如下所示:
(0, 0, 0) =>0
(0, 0, 1) =>1
(0, 0, 1) =>1
(0, 0, 2) =>2
(0, 0, 2) =>2
(0, 0, 1) =>1
(0, 0, 1) =>1
(0, 0, 1) =>1
(0, 0, 2) =>2
(0, 0, 2) =>2
(0, 0, 1) =>1
(0, 1, 1) =>2
答案 0 :(得分:4)
如果您仅使用python >= 3.6
打印,则可以使用f字符串,只需执行以下操作:
import itertools
thelist = [0, 0, 0, 1, 1, 2, 2, 1]
for L in range(3,4):
for subset in itertools.combinations(thelist, L):
print(f"{subset} => {sum(subset)}")
对于Python <3.6
,请使用:print("{} => {}".format(subset, sum(subset))