lambda函数用于对字典中值的乘积求和

时间:2013-05-29 04:12:32

标签: python dictionary lambda

my_dict = {'a1':2,'a2':3,'b1':1,'b2':5,'b3':8}

我想将标签'a'和'b'的产品用相同的数字相加。

result = a1*b1 + a2*b2

注意:b3被忽略,因为它没有相应的a3。

我的代码:

result = sum (lambda x * y, if str(key)[0] == a and str(key)[0] ==b and str(key)[1] == str(key)[1], my_dict) 

4 个答案:

答案 0 :(得分:1)

my_dict = {'a1':2,'a2':3,'b1':1,'b2':5,'b3':8}
result = 0

for i in range(1, (len(my_dict) + 1) / 2):
    if not my_dict.has_key("a" + str(i)) \
        or not my_dict.has_key("b" + str(i)):
        break
    result += my_dict["a" + str(i)] * my_dict["b" + str(i)]

答案 1 :(得分:1)

你有足够的逻辑,你应该可能将你的过滤器分解为一个单独的函数:

my_dict = {'a1':2,'a2':3,'b1':1,'b2':5,'b3':8}

def filtered(d):
    for key in d:
        if not key.startswith('a'):
            continue

        b_key = "b" + key[1:]

        if b_key not in d:
            continue

        yield d[key], d[b_key]

sum(a * b for a, b in filtered(my_dict))

答案 2 :(得分:1)

from itertools import combinations
mydict={'a1':2,'a2':3,'b1':1,'b2':5,'b3':8}

result=sum(mydict[x]*mydict[y] for x,y in combinations(mydict.keys(),2) if x[1]==y[1])

答案 3 :(得分:1)

from collections import defaultdict
from functools import reduce
from operator import mul

my_dict = {'a1':2,'a2':3,'b1':1,'b2':5,'b3':8}

D = defaultdict(dict)

for k in my_dict:
    a, b = k
    D[b][a] = my_dict[k]

print sum(reduce(mul, d.values()) for d in D.values() if len(d) >= 2)

17