gpt4 book ai didi

Python - 字典中的递归循环

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:27 24 4
gpt4 key购买 nike

有没有一种很酷的方法可以递归遍历dict以获得sum(values)的所有组合:

我有一个字典 {a: 10, b: 20, c:30}

我想找到所有二元组和三元组的唯一组合(值的总和):

例如两个

30  # 10 + 20
40 # 10 + 30
50 # 20 + 30

对于三分球也是如此:

60 # 10 + 20 + 30

最佳答案

对于您提供的示例输入,您可以使用 mapsumitertools.combinations 的组合:

d = {'a': 10, 'b': 20, 'c':30}

import itertools
print map(sum, itertools.combinations(d.values(), 2))
print map(sum, itertools.combinations(d.values(), 3))

或者,在 Python3 中:

d = {'a': 10, 'b': 20, 'c':30}

import itertools
print(list(map(sum, itertools.combinations(d.values(), 2))))
print(list(map(sum, itertools.combinations(d.values(), 3))))

打印:

[40, 30, 50]
[60]

关于Python - 字典中的递归循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23526841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com