1
基本上这是一个组合程序。它汇总了dict1中的所有值,并返回所有添加到100的组合键。我想得到相同的结果,但我不希望某些键/值位于同一组合组中。即我不想键“A”是在与键“B”,键“c”的任何组合基团不以任何组合组“d”等返回字典的某些总和值
import itertools
dict1 = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'f':8}
def matches(d, target):
# First try single items, then couples, then triplets etc.
for num in range(1,len(d)+1):
# Iterate over all possible combinations of length num
for com in itertools.combinations(d.items(), num):
# Does the sum of all second items per key/value pair match the target?
if sum(item[1] for item in com) == target:
# Yield one item at a time, so the caller can decide when to stop
yield dict(com).keys()
for match in matches(dict1, 100):
print(match)
您的代码是否工作?它在做什么,它不应该?它应该怎么做呢?你的问题是什么,请具体说明一下?请为示例输入包含所需的和实际的输出。 – wwii