1
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

4 回答 4

1

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))
于 2013-05-29T04:30:35.507 回答
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
于 2013-05-29T05:16:20.590 回答
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)]
于 2013-05-29T04:23:54.030 回答
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])
于 2013-05-29T04:50:22.093 回答