为什么在尝试做点积时会出现 TypeError?

Why do I get TypeError when trying to do dot product?

如果我有一个整数并将它乘以容器(元组)中的每个整数,然后将它们相加——类似于点积——我会得到正确答案。当我将它们转换为浮点数时,出现 TypeError:

TypeError: 无法将序列乘以 'float'

类型的非整数
sig = {'a': 1.0, 'b': 2.0, 'c': 3.0}
exp = {'a': (1.0,2.0,3.0), 'b': (1.0,2.0,3.0), 'c': (1.0,2.0,3.0)}
man_dot = {'a': 1*1+1*2+1*3, 'b': 2*1+2*2+2*3, 'c': 3*1+3*2+3*3}

weighted_dict = {}
for s in sig:
    print("this is s:\n{}".format(s))
    for e in exp:
        print("this is e:\n{}".format(e))
        weighted_dict[s] = sum(sig[s] * exp[e])
# weighted_dict should be equivalent to man_dot
# weighted_dict should be {'a': 6, 'c': 18, 'b': 12}

此脚本必须处理浮点数操作,那么如何修改它才能做到这一点?为什么会这样?使用一些面向数学的库有更好的方法吗?

您的问题是您试图将 (1.0, 2.0, 3.0) 乘以 1.0,这会产生上述错误。尝试以下操作:

sig = {'a': 1.0, 'b': 2.0, 'c': 3.0}
exp = {'a': (1.0,2.0,3.0), 'b': (1.0,2.0,3.0), 'c': (1.0,2.0,3.0)}
man_dot = {'a': 1*1+1*2+1*3, 'b': 2*1+2*2+2*3, 'c': 3*1+3*2+3*3}

weighted_dict = {}
for s in sig:
    print("this is s:\n{}".format(s))
    for e in exp:
        print("this is e:\n{}".format(e))
        weighted_dict[s] = sum([sig[s] * item for item in exp[e]])

>>> weighted_dict
{'c': 18.0, 'a': 6.0, 'b': 12.0}
>>>