gpt4 book ai didi

Python,打印出字典中每个可能组合的元素总和的键

转载 作者:太空宇宙 更新时间:2023-11-04 00:12:24 25 4
gpt4 key购买 nike

创建以下行以迭代和总结字典中每个可能的元素组合。例如,如果字典的长度是 5,我想要任意 2 个元素、任意 3 个元素、任意 4 个元素的总和。

import itertools

di = {'a': 1, 'b': 2, 'c': 34, 'd': 24}

dict_len = range(len(di)-2, len(di))

for l in dict_len:
d_values = list(itertools.combinations(di.values(), l))
for d in d_values:
print d

输出:

35
3
25
36
58
26
37
59
27
60

我怎样才能同时打印出值的键?喜欢:

a + c = 35
a + b = 3
a + d = 25
b + c = 36
c + d = 58
b + d = 26
a + b + c =37
a + c + d =59
a + b + d =27
c + b + d =60

谢谢。

最佳答案

要获得所需的输出(如问题中所述):

import itertools

di = {'a': 1, 'b': 2, 'c': 34, 'd': 24}

dict_len = range(len(di)-2, len(di))

for l in dict_len:
d_values = list(itertools.combinations(di.values(), l))
d_keys = list(itertools.combinations(di.keys(), l))
for i in range(len(d_values)):
print " + ".join(d_keys[i]), "=", sum(d_values[i])

输出:

a + c = 35
a + b = 3
a + d = 25
c + b = 36
c + d = 58
b + d = 26
a + c + b = 37
a + c + d = 59
a + b + d = 27
c + b + d = 60

关于Python,打印出字典中每个可能组合的元素总和的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52070997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com