列出一组给定数字的组合及其总数

时间:2018-10-21 10:48:05

标签: python combinations

我使用这段代码从一组给定的列表中生成三个数字的组合。

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

1 个答案:

答案 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))