【问题标题】:Why do I get TypeError when trying to do dot product?为什么在尝试做点积时会出现 TypeError?
【发布时间】:2015-04-17 03:43:17
【问题描述】:

如果我有一个整数并将其乘以容器(元组)中的每个整数并将它们相加——类似于点积——我会得到正确的答案。当我将它们转换为浮点数时,我得到一个 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}

这个脚本必须处理浮动操作,那么我该如何修改它呢?为什么会这样?使用一些面向数学的库有没有更好的方法?

【问题讨论】:

    标签: python-3.x dot-product


    【解决方案1】:

    您的问题是您试图将(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}
    >>> 
    

    【讨论】:

    • 很好的建议,谢谢。所以问题是我未能遍历 {exp} 的元组值。但为什么它适用于整数而不适用于浮点数?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2021-12-11
    • 2018-11-10
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 2021-07-24
    相关资源
    最近更新 更多