首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回字典的某些求和值

问返回字典的某些求和值
EN

Stack Overflow用户
提问于 2015-07-20 05:44:33
回答 1查看 50关注 0票数 1

基本上,这是一个组合程序。它对dict1中的所有值求和,并返回所有加到100的组合键。我希望得到相同的结果,但我不希望某些键/值在同一个组合组中。例如,我不希望密钥'a‘在任何带有密钥'b’的组合组中,密钥'c‘不在任何带有'd’的组合组中,等等。

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2015-07-20 07:16:45

主要的问题是,程序的逻辑不能以这种形式工作。

sum(item[1] for item in com)的最大值是30,然后循环结束。因此,函数matches不会yield任何东西。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31506242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档