Python 如何对字典中的键进行排序,如果组合值等于某个数字,则添加值并返回键列表

Python 如何对字典中的键进行排序,如果组合值等于某个数字,则添加值并返回键列表,python,dictionary,Python,Dictionary,我有一个包含不同整数值的键的字典,例如 d = {'a':1, 'b':12, 'c':33, 'd':40, 'e':15, 'f':6, 'g':27} 我希望能够返回组合值等于某个数字的键列表,例如 number = 55 result = ['d', 'e'] 我不确定如何处理这个问题,或者我是否应该反复思考这个问题。这件事我有点不知所措。 目前我正在使用Python2.7,但也不介意看到Python3中的解决方案。 老实说,在这个阶段,即使是建议也会受到欢迎。1)对字典进行排序以创

我有一个包含不同整数值的键的字典,例如

d = {'a':1, 'b':12, 'c':33, 'd':40, 'e':15, 'f':6, 'g':27}
我希望能够返回组合值等于某个数字的键列表,例如

number = 55
result = ['d', 'e']
我不确定如何处理这个问题,或者我是否应该反复思考这个问题。这件事我有点不知所措。 目前我正在使用Python2.7,但也不介意看到Python3中的解决方案。 老实说,在这个阶段,即使是建议也会受到欢迎。

1)对字典进行排序以创建元组列表。
2) 现在,对于排序列表中的每个索引
i
,查找其索引
j
索引i处的和值等于索引j处的值

a= {'a':1, 'b':12, 'c':33, 'd':40, 'e':15, 'f':6, 'g':27}
# Lets sort it first
a_sort = sorted(a.items(),key=lambda x:x[1])
n=len(a)
i=j=flag=0
sum=55 #Input the sum from user
result = []
while i<n:
        j=i+1
        while j<n:
                if (sum-a_sort[i][1]) == a_sort[j][1] :
                        result.append(a_sort[j][0])
                        result.append(a_sort[i][0])
                        flag=1
                        break
                else:
                        j=j+1
        if flag==1:
                break
        i=i+1

print result

只要项目数量不太多,您就可以强制执行以下操作:

import itertools
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 com
您可以使用它来迭代所有匹配项:

>>> mydict = {'a':1, 'b':12, 'c':33, 'd':40, 'e':15, 'f':6, 'g':27}
>>> for match in matches(mydict,55):
...     print(match)
...
(('d', 40), ('e', 15))
(('c', 33), ('e', 15), ('f', 6), ('a', 1))
(('b', 12), ('e', 15), ('g', 27), ('a', 1))

或者在
print()
行之后添加一个
break
,使程序在第一次匹配时停止。

谢谢。你的代码可以工作,但我在理解发生了什么方面有点困难。我对Python比较陌生,所以我的下一个任务将是理解您的代码。再次感谢。我喜欢你在那里做的事。它比我预期的更优雅,我可以了解正在发生的事情,尽管我不熟悉itertools和组合。谢谢你的帮助。@ErmahgerdLulz:我添加了一些评论;你绝对应该去看看这本书。当你在做的时候,也要读一读关于它有很多非常有用的东西。非常感谢
>>> mydict = {'a':1, 'b':12, 'c':33, 'd':40, 'e':15, 'f':6, 'g':27}
>>> for match in matches(mydict,55):
...     print(match)
...
(('d', 40), ('e', 15))
(('c', 33), ('e', 15), ('f', 6), ('a', 1))
(('b', 12), ('e', 15), ('g', 27), ('a', 1))