有没有一种方法可以在不使用Python中的NumPy或Operation模块的情况下执行包含值的两个列表的点积?这样代码就能够尽可能地简单。
例如:
V_1=[1,2,3]
V_2=[4,5,6]
Dot(V_1,V_2)
答案:32
如果没有NumPy,您可以编写一个使用zip
和sum
的函数来实现点积。
>>> def dot(v1, v2):
... return sum(x*y for x, y in zip(v1, v2))
...
>>> dot([1, 2, 3], [4, 5, 6])
32
从Python 3.10开始,您可以使用zip(v1, v2, strict=True)
来确保v1
和v2
具有相同的长度。
def dot_product(x, y):
dp = 0
for i in range(len(x)):
dp += (x[i]*y[i])
return dp
sample1 = [1,2,3,4,5]
sample2 = [2,1,1,1,1]
dot_product(sample1, sample2) #16
import numpy as np
x = np.array([25, 2, 5])
y = np.array([0, 1, 2])
print(x@y)
12
@
运算符是由 NumPy 实现的,它不是 Python 的本地部分。 - Neil C. Obremski