嵌套数组中带有浮点数的点积

Dot product with floats in nested arrays

我正在尝试使用纯基础 python(没有导入或第 3 方库)来实现点积函数。对于一个整数数组,我知道我可以使用下面的函数:

def dot(v1, v2):
    return sum(x*y for x,y in zip(v1,v2))

但是,我的数组是浮点数:

lista = [[2.62, -3.97], [-2.32, -1.30], [-1.09, -0.45]]
listb = [-0.75, 2.75]

当我尝试 print(dot(lista, listb)) 时,我得到:

TypeError: can't multiply sequence by non-int of type 'list'

我该如何纠正?

您需要再遍历一层才能执行乘法:

lista = [[2.62, -3.97], [-2.32, -1.30], [-1.09, -0.45]]
listb = [-0.75, 2.75]
final_results = [sum(a*b for a, b in zip(listb, i)) for i in lista]

输出:

[-12.8825, -1.8350000000000004, -0.41999999999999993]

或者,使用带有 map 的函数:

def dot(m, n = [-0.75, 2.75]):
  return sum(a*b for a, b in zip(m, n))

print(list(map(dot, lista)))

我怀疑您使用的是 Matlab 或类似语言,在这种语言中,为一维编写的内容会自动在更高维中运行。这是因为 Matlab 支持所谓的 array-oriented programming。 Python没有这个功能,只能手动遍历数组

map(lambda x: dot(x, listb), lista)