【问题标题】:Determine if any complex numbers exist in a matrix确定矩阵中是否存在复数
【发布时间】:2021-02-28 21:21:54
【问题描述】:

我正在编写一个函数来确定矩阵的元素是否复杂。我希望该函数返回TrueFalse。我有这段代码,但它似乎没有按预期工作:

def confirm_matrix(M):
    row_1_length = len(M[0])
    if len(M)>0:
        for row in M:
            if type(row) is not list or tuple:
                return False
            for row in M[1:]:
                if len(row)!= row_1_length:
                    return False
                for row in M:
                    for element in row:
                        try:
                            isinstance(element, complex) == True
                            return True
                        except:
                            return False
confirm_matrix([[1j,1j],[2j,2j]])

我希望得到True,但这给出了False。我可以在这里的代码中改进什么?

【问题讨论】:

标签: python python-3.x list matrix nested-for-loop


【解决方案1】:

这里的逻辑是多余的。如果您的矩阵始终是 2d,您可以迭代行和列并将生成器传递给 any

>>> M = [[1j,1j],[2j,2j]]
>>> any(isinstance(x, complex) for row in M for x in row)
True
>>> M = [[1,1],[2,2]]
>>> any(isinstance(x, complex) for row in M for x in row)
False

如果你使用的是 numpy,np.iscomplex() 是最好的选择:

>>> a = np.array([[1+1j, 1+0j], [4.5, 3]])
>>> np.iscomplex(a).any()
True

【讨论】:

  • 当然可以!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-04
  • 2018-01-15
  • 2012-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多