Python 返回字典的某些和值

Python 返回字典的某些和值,python,python-3.4,Python,Python 3.4,基本上这是一个组合方案。它将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

基本上这是一个组合方案。它将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)

主要的问题是,程序的逻辑在这种形式下不起作用


总和的最大值(com中项的项[1])
30
,然后循环结束。因此,函数
匹配
不会
产生任何东西。

主要问题是,程序的逻辑在这种形式下不起作用


总和的最大值(com中项的项[1])
30
,然后循环结束。因此,函数
匹配
不会
产生任何东西。

您的代码工作吗?它在做什么不该做的事?它做了什么不应该做的事?你的问题是什么,请具体说明?请在示例输入中包含所需和实际的输出。您的代码有效吗?它在做什么不该做的事?它做了什么不应该做的事?你的问题是什么,请具体说明?请在示例输入中包含所需和实际输出。