如何在Python中将两个2D数组合并为以下内容? [英] How to combine two 2D array into the following in Python?

查看:106
本文介绍了如何在Python中将两个2D数组合并为以下内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有2个2D数组,如下所示:

Suppose I have 2 2D array as follows:

A = [[1, 2],
     [3, 4]]

B = [[5, 6, 7],
     [8, 9, 8],
     [7, 6, 5]]

是否有一个numpy函数将A和B组合成C,如下所示?

Is there a numpy function to combine A and B into C as follows?

C = [[1, 2, 0, 0, 0],
     [3, 4, 0, 0, 0],
     [0, 0, 5, 6, 7],
     [0, 0, 8, 9, 8],
     [0, 0, 7, 6, 5]]

谢谢

推荐答案

如果您希望进行许多线性代数运算,请 NumPy / SciPy 将是您的朋友.对于创建块对角矩阵的特定问题, 保存一天:

If you expect to be making many linear algebraic operations, NumPy/SciPy will be your friend. For the particular problem of creating block diagonal matrices, scipy.linalg.block_diag saves the day:

In [14]: from scipy.linalg import block_diag

In [16]: A = [[1, 2],
    ...:      [3, 4]]
    ...:

In [17]: B = [[5, 6, 7],
    ...:      [8, 9, 60],
    ...:      [10, 20, 0]]
    ...:

In [18]: block_diag(A, B)
Out[18]:
array([[ 1,  2,  0,  0,  0],
       [ 3,  4,  0,  0,  0],
       [ 0,  0,  5,  6,  7],
       [ 0,  0,  8,  9, 60],
       [ 0,  0, 10, 20,  0]], dtype=int32)

否则(请注意,原始形式的问题实际上并未指定所需的解决方案涉及NumPy),如果您只想使用香草Python,并假设所有块都是正方形,则可以执行以下操作

Otherwise (edit: noting that the question in its original form did not actually specify that the desired solution involved NumPy), if you just want to do it with vanilla Python, assuming that all blocks are square you could do something like

[a + [0]*len(B) for a in A] + [[0]*len(A) + b for b in B]

这篇关于如何在Python中将两个2D数组合并为以下内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆