计算点积的Pythonic方法是什么?
我有两个列表,一个名为 A,另一个名为 B。A 中的每个元素都是一个三元组,B 中的每个元素只是一个数字。我想计算的结果定义为:
result = A[0][0] * B[0] + A[1][0] * B[1] + ... + A[n-1][0] * B[n-1]
我知道逻辑很简单,但如何以Pythonic方式编写?
谢谢!
I have two lists, one is named as A, another is named as B. Each element in A is a triple, and each element in B is just an number. I would like to calculate the result defined as :
result = A[0][0] * B[0] + A[1][0] * B[1] + ... + A[n-1][0] * B[n-1]
I know the logic is easy but how to write in pythonic way?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
Python 3.5 有一个用于点积的显式运算符
@
,所以你可以写
而不是
Python 3.5 has an explicit operator
@
for the dot product,so you can write
instead of
http://docs.scipy.org/doc/numpy/reference/
如果您想要在没有 numpy 的情况下做到这一点,请尝试
http://docs.scipy.org/doc/numpy/reference/
If you want to do it without numpy, try
我最喜欢的 Pythonic 点产品是:
因此,对于您的情况,我们可以这样做:
My favorite Pythonic dot product is:
So for your case we could do:
使用运算符和 itertools 模块:
Using the operator and the itertools modules:
使用
more_itertools
,一个实现dotproduct
itertools 配方:Using
more_itertools
, a third-party library that implements thedotproduct
itertools recipe:人们正在将 @ 运算符重新指定为点积运算符。这是我的代码,使用普通 python 的 zip 返回一个元组。然后使用列表理解而不是映射。
People are re-assigning the @ operator as the dot product operator. Here's my code using vanilla python's zip which returns a tuple. Then uses list comprehension instead of map.
就是这样。
And that's it.
在 Python 3.12+ 中,您可以使用
math.sumprod
。鉴于您的情况,
您可以计算
A[0][0] * B[0] + A[1][0] * B[1]
在旧版本中,最Pythonic的方法可能是使用使用生成器求和(即不构建中间列表):
In Python 3.12+ you can use
math.sumprod
.Given your situation
you can compute
A[0][0] * B[0] + A[1][0] * B[1]
withIn older versions the most pythonic way is probably to use
sum
with a generator (i.e., without building an intermediate list):对于这种事情来说,最Pythonic的方法可能是使用 numpy< /a>. ;-)
Probably the most Pythonic way for this kind of thing is to use numpy. ;-)
但是,这可能是重复的解决方案:
在普通
Python
中:或使用
numpy
(如 用户57368的回答):This might be repeated solution, however:
In plain
Python
:Or using
numpy
(as described in user57368's answer) :以上所有答案都是正确的,但在我看来,计算点积的最Pythonic方法是:
All above answers are correct, but in my opinion the most pythonic way to calculate dot product is: