[英]Python - recursive loop within a dict
是否有一种很酷的方法可以递归遍历dict以获取sum(values)的所有组合:
我有一个字典{a: 10, b: 20, c:30}
我想找到所有三和三的独特组合(值的总和):
例如二
30 # 10 + 20
40 # 10 + 30
50 # 20 + 30
类似的三分:
60 # 10 + 20 + 30
对于您提供的示例输入,可以使用map
, sum
和itertools.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]
您可以使用itertools.combinations
获得所有组合,然后对结果求和。
例如
from itertools import combinations
mydict = {'a': 10, 'b': 20, 'c':30}
twos = [sum(c) for c in combinations(mydict.values(), 2)]
threes = [sum(c) for c in combinations(mydict.values(), 3)]
print twos
print threes
您可以按以下方式使用itertools
:
import itertools
mydict = {'a': 10, 'b': 20, 'c':30}
result = [mydict[x] + mydict[y] for x, y in itertools.combinations(d, 2)]
注意:以上combinations
使用的解决方案更好! 但是我还是要保留这个。
from itertools import permutations
data = {'a': 10, 'b': 20, 'c':30}
for key_perm in permutations(data.keys(), 2):
print ' + '.join(key_perm), '=', sum(data[k] for k in key_perm)
印刷品:
a + c = 40
a + b = 30
c + a = 40
c + b = 50
b + a = 30
b + c = 50
但是由于整数的加法是可交换的,可能只需要不同的和。 集来救援。
for key_perm in set(tuple(sorted(perm)) for perm in permutations(data.keys(), 2)):
print ' + '.join(key_perm), '=', sum(data[k] for k in key_perm)
印刷品:
b + c = 50
a + b = 30
a + c = 40
需要使用上面的tuple
,因为set()
仅接受不可变的项, sorted()
返回一个可变list
。
功率设定:
d={'a': 10, 'b': 20, 'c':30}
def power_set(items):
n = len(items)
for i in xrange(2**n):
combo = []
for j in xrange(n):
if (i >> j) % 2 == 1:
combo.append(items[j])
yield combo
data= [sum(x) for x in list(power_set(d.values())) if len(x)>1]
In [10]: data
Out[10]: [40, 30, 50, 60]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.