在 Python 中拆分矩阵

Splitting a Matrix in Python

我想将任何矩阵(很可能是 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?

谢谢!

是的,你可以这样做:

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])

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

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 

示例:

matrix = [
 [1, 0, 0, 4],
 [1, 0, 0, 2],
 [4, 3, 1, 6]
]

a, b = split(matrix)

print("A: %s" % str(a)) # Output ==> A: [[1, 0, 0], [1, 0, 0], [4, 3, 1]]
print("B: %s" % str(b)) # Output ==> B: [4, 2, 6]