使用itertools.combinations:
d = {'A':12, 'B':1, 'C':14, 'D':13, 'E':3, 'F': 4}
import itertools
for a, b, c in itertools.combinations(sorted(d, key=d.get), 3):
if d[a] + d[b] == d[c]:
print(a,b,c)
B E F
B A D
B D C
更新
如果您想要重复使用itertools.combinations_with_replacement:
d = {'A':1, 'B':2, 'C':4}
import itertools
for a, b, c in itertools.combinations_with_replacement(sorted(d, key=d.get), 3):
if d[a] + d[b] == d[c]:
print(a,b,c)
A A B
B B C
为什么sorted使用?
比较x + y==z是没有意义的,如果xor yis 大于z。(假设所有值都是正整数)。我sorted以前是整理数据的; x <= y <= z.
排序的另一个副作用:如果A + B == C为真,B + A == C则也为真。但是使用sorted,只打印一个。
顺便说一句,不要dict用作变量名。它隐藏了内置dict函数。