在下面创建几行以迭代和求和字典中的每种可能的元素组合。例如,如果字典的长度为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
谢谢。
答案 0 :(得分:1)
您可以这样:
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 d,k in zip(d_values,d_keys):
print(k,sum(d))
哪个生成输出:
('a', 'b') 3
('a', 'c') 35
('a', 'd') 25
('b', 'c') 36
('b', 'd') 26
('c', 'd') 58
('a', 'b', 'c') 37
('a', 'b', 'd') 27
('a', 'c', 'd') 59
('b', 'c', 'd') 60
答案 1 :(得分:1)
要获得所需的输出(在问题中指定):
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
答案 2 :(得分:1)
有趣的问题。您可以这样做:
import itertools
di = {'a': 1, 'b': 2, 'c': 34, 'd': 24}
for n in range(2, len(di)):
for pairs in itertools.combinations(di.items(), n):
keys, values = zip(*pairs) # Note 1
print("{} = {}".format(' + '.join(keys), sum(values)))
这将导致
a + b = 3
a + c = 35
a + d = 25
b + c = 36
b + d = 26
c + d = 58
a + b + c = 37
a + b + d = 27
a + c + d = 59
b + c + d = 60
注意:
zip(*iterable)
构造会更改分组顺序。例如,它将您从[('foo', 1), ('bar', 2)]
带到[('foo', 'bar'), (1, 2)]
,从而有效地将keys
和values
分组在一起。