问题描述
我需要计算字典中两个键的点积。
res = {'Ben':['5','0','1','4','2'...],'Moose': ['5','5','3'...]}
我想制作这样的东西。我想将 Ben 的值与 Moose 的值相乘。
Ans = 31 [5*5 + 0*5 + 0*0 + 0*0 + 1*0 + 4*0 + 2*3...]
我怎样才能用字典做到这一点?有了这个列表,我可以直接调用 np.dot 函数或者写一个小循环。
解决方法
您可以在形成点积的列表推导式上使用 sum
:
res = {'Ben':['5','0','1','4','2'],'Moose': ['5','5','3']}
ans = sum(int(b) * int(m) for b,m in zip(res['Ben'],res['Moose']))
print(ans)
输出:
31
,
使用 zip
和 sum
的一种方式:
sum(int(i) * int(j) for i,j in zip(*res.values()))
输出:
31
如果键的数量是动态的(因此列表的数量是动态的),您可以使用 operator.mul
和 functools.reduce
创建一个可扩展的函数:
# Sample data with 3 keys
res3 = {'Ben':['5','3'],'Chris': ['5','3']}
from operator import mul
from functools import reduce
def cummul(iterable):
return reduce(mul,(int(i) for i in iterable))
sum(cummul(it) for it in zip(*res3.values()))
输出:
143
,
对于 dict 中的任何键,只需使用 math
和 zip
。请注意,math.prod
需要 python 3.8 或更高版本:
sum(math.prod(map(int,i)) for i in zip(*res.values()))
,
您可以使用 zip
并按如下方式一起迭代两个键:
sum = 0
for x,y in zip(res['Ben'],res['Moose']):
sum += int(x) * int(y)
print(sum)
,
您可以执行类似的操作:
res = {'Ben':['5','3']}
ans = {}
for k,v in res.items():
if(len(ans.keys())) == 0:
ans = v
ans_temp = [v1*v2 for v1,v2 in zip(ans,v)]
ans = ans_temp
print(sum(ans))
这应该适用于任意长度的字典。
,使用 numpy
数组是个好主意,它可以让您的代码更短、更清晰、更易读:
import numpy as np
x = np.array([[int(j) for j in i] for i in list(res.values())])
ans = x.prod(axis=0).sum()
print(ans)
无论 res
中有多少项,上述代码都可以正常工作。