知道传递给函数的参数是向量还是矩阵

2024-04-19 12:57:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Sage编写一个函数,它应该以不同的方式处理向量和矩阵。你知道吗

我不能使用isinstance函数,因为向量或矩阵的类型取决于元素的类型:

sage: type(matrix([[1]]))
<type 'sage.matrix.matrix_integer_dense.Matrix_integer_dense'>
sage: type(matrix([[i]]))
<type 'sage.matrix.matrix_symbolic_dense.Matrix_symbolic_dense'>

区分向量和矩阵的最佳方法是什么?你知道吗


Tags: 函数元素类型type方式矩阵integer向量
1条回答
网友
1楼 · 发布于 2024-04-19 12:57:24

尝试在Sage源代码中查找定义matrix.dim时意外找到了解决方案。你知道吗

from sage.matrix.matrix import is_Matrix
from sage.structure.element import is_Vector

def myfunction(x):
    if is_Vector(x):
        # do something
    elif is_Matrix(x):
        # do something else
    else:
        raise TypeError("The argument must be vector or matrix")

相关问题 更多 >