在Python中拆分矩阵

时间:2017-11-05 02:32:39

标签: python matrix gaussian

我想将任何矩阵(最有可能是3x4)分成两部分。一部分是左手,然后是右手 - 只有最后一列。

[[1,0,0,4],              [[1,0,0],       [4,
 [1,0,0,2],     ---> A=   [1,0,0],   B =  2,
 [4,3,1,6]]               [4,3,1]]        6]

有没有办法在python中执行此操作并将其分配为A和B?

谢谢!

2 个答案:

答案 0 :(得分:1)

是的,你可以这样做:

def split_last_col(mat):
    """returns a tuple of two matrices corresponding 
    to the Left and Right parts"""
    A = [line[:-1] for line in mat]
    B = [line[-1] for line in mat]
    return A, B

split_last_col([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

输出:

([[1, 2], [4, 5], [7, 8]], [3, 6, 9])

答案 1 :(得分:0)

您可以手动创建A和B,如下所示:

<root>route
            <child>T40
                <position>1</position>
   </child>
   <child>D55
                <position>2</position>
   </child>

或使用列表理解:

def split(matrix):
  a = list()
  b = list()

  for row in matrix:
    row_length = len(row)
    a_row = list()

    for index, col in enumerate(row):
      if index == row_length - 1:
        b.append(col)
      else:
        a_row.append(col)
    a.append(a_row)
  return a, b

示例:

def split(matrix):
  a = [row[:len(row) - 1] for row in matrix]
  b = [row[len(row) - 1] for row in matrix]
  return a, b