更新时间:2023-11-25 23:26:58
这就是为什么 Python 的 sum
函数 有一个可选的开始"参数:所以你可以用你添加的那种零对象"来初始化它.在这种情况下,使用零矩阵.
My python list contains sympy matrix object, and I need to sum them all. If all list elements are just symbols, then using built-in sum function in python works fine.
import sympy as sp
x = sp.symbols('x')
ls = [x, x+1, x**2]
print(sum(ls))
>>> x**2 + 2*x + 1
But for the elements of matrix type, sum function looks not working.
import sympy as sp
ls = [sp.eye(2), sp.eye(2)*5, sp.eye(2)*3]
print(sum(ls))
>>> TypeError: cannot add <class 'sympy.matrices.dense.MutableDenseMatrix'> and <class 'int'>
How can I resolve this problem?
This is why Python's sum
function has an optional "start" argument: so you can initialize it with a "zero object" of the kind you are adding. In this case, with a zero matrix.
>>> print(sum(ls, sp.zeros(2)))
Matrix([[9, 0], [0, 9]])