加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Python中真的有一个@运算符来计算点积吗?

发布时间:2020-12-20 12:02:10 所属栏目:Python 来源:网络整理
导读:这个答案是否正确: https://stackoverflow.com/a/39662710/1175080? 引用那个答案. In Python 3.5,there is a new operator for the dot product,so you can write a= A @ B instead of a= numpy.dot(A,B) 它似乎对我不起作用. $python3Python 3.6.1 (defa
这个答案是否正确: https://stackoverflow.com/a/39662710/1175080?

引用那个答案.

In Python 3.5,there is a new operator for the dot product,so you
can write a= A @ B instead of a= numpy.dot(A,B)

它似乎对我不起作用.

$python3
Python 3.6.1 (default,Apr  4 2017,09:40:21) 
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help","copyright","credits" or "license" for more information.
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a @ b
Traceback (most recent call last):
  File "<stdin>",line 1,in <module>
TypeError: unsupported operand type(s) for @: 'list' and 'list'
>>>

但是相关的答案已经获得了6个赞成票,所以我必须遗漏一些东西.您能否提供一个完整的示例,说明如何使用@运算符计算点积?

解决方法

见 what’s new in Python 3.5,section matrix mult (PEP 465):

PEP 465 adds the @ infix operator for matrix multiplication. Currently,no builtin Python types implement the new operator,however,it can be implemented by defining __matmul__(),__rmatmul__(),and __imatmul__() for regular,reflected,and in-place matrix multiplication. The semantics of these methods is similar to that of methods defining other infix arithmetic operators.

所以,你必须自己实现这些方法.

或者,使用已经支持new运算符的numpy> = 1.10:

>>> import numpy
>>> x = numpy.ones(3)
>>> m = numpy.eye(3)
>>> x @ m
array([ 1.,1.,1.])

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读