简体   繁体   中英

lambda function to sum products of values from a dictionary

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

I want to sum the products of labels 'a' and 'b' with the same numbers.

result = a1*b1 + a2*b2

note: b3 is ignored, since it has no corresponding a3.

my code:

result = sum (lambda x * y, if str(key)[0] == a and str(key)[0] ==b and str(key)[1] == str(key)[1], my_dict) 
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)]

You have enough logic here that you should probably break out your filter into a separate function:

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))
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])
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM