什么是' @ ='在Python中的符号?

时间:2014-12-09 17:59:35

标签: python python-3.x operators matrix-multiplication python-3.5

我知道@适用于装饰器,但Python中的@=是什么?这只是对未来想法的保留吗?

这只是阅读tokenizer.py时的众多问题之一。

3 个答案:

答案 0 :(得分:162)

来自the documentation

  

@(at)运算符旨在用于矩阵乘法。没有内置的Python类型实现此运算符。

在Python 3.5中引入了@运算符。正如您所期望的那样,@=是矩阵乘法,然后是赋值。它们映射到__matmul____rmatmul____imatmul__,类似于++=映射到__add____radd__或{{ 1}}。

PEP 465中详细讨论了算子及其背后的基本原理。

答案 1 :(得分:42)

@=@是Python 3.5 中执行矩阵乘法的新运算符。它们旨在澄清到目前为止存在的运算符*的混淆,运算符用于元素乘法或矩阵乘法,这取决于特定库/代码中使用的约定。因此,将来,运算符*仅用于逐元素乘法。

PEP0465中所述,引入了两个运营商:

  • 新的二元运算符A @ B,与A * B
  • 类似
  • 就地版本A @= B,与A *= B
  • 类似

矩阵乘法与元素乘法

快速突出显示两个矩阵的区别:

A = [[1, 2],    B = [[11, 12],
     [3, 4]]         [13, 14]]
  • 元素乘法将产生:

    A * B = [[1 * 11,   2 * 12], 
             [3 * 13,   4 * 14]]
    
  • 矩阵乘法将产生:

    A @ B  =  [[1 * 11 + 2 * 13,   1 * 12 + 2 * 14],
               [3 * 11 + 4 * 13,   3 * 12 + 4 * 14]]
    
Numpy中的用法

到目前为止,Numpy使用了以下惯例:

@运算符的引入使得涉及矩阵乘法的代码更容易阅读。 PEP0465给我们举了一个例子:

# Current implementation of matrix multiplications using dot function
S = np.dot((np.dot(H, beta) - r).T,
            np.dot(inv(np.dot(np.dot(H, V), H.T)), np.dot(H, beta) - r))

# Current implementation of matrix multiplications using dot method
S = (H.dot(beta) - r).T.dot(inv(H.dot(V).dot(H.T))).dot(H.dot(beta) - r)

# Using the @ operator instead
S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)

显然,最后一个实现更易于阅读和解释为方程式。

答案 2 :(得分:2)

@是Python3.5中添加的Matrix Multiplication的新运算符

参考:https://docs.python.org/3/whatsnew/3.5.html#whatsnew-pep-465

实施例

C = A @ B
相关问题