基于公认的答案:为了完整性,这里有一个更通用的解决方案。
def row_by_row_concatenation_of_two_arrays(arr0, arr1):
"""Combine two arrays using row by row concatenation.
Example
=======
arr0: arr1:
[[1,2,3], [[1,2],
[4,5,6], [3,4]]
[7,8,9]]
Into form of:
[[1,2,3,1,2],
[1,2,3,3,4],
[4,5,6,1,2],
[4,5,6,3,4],
[7,8,9,1,2],
[7,8,9,3,4]]
"""
arr0_repeated = np.repeat(arr0, repeats=arr1.shape[0], axis=0)
arr1_tiled = np.tile(arr1, (arr0.shape[0], 1))
return np.hstack((arr0_repeated, arr1_tiled))
使用该函数
functools.reduce
:
In [11]: from module import row_by_row_concatenation_of_two_arrays
In [12]: import functools
In [13]: x=((1.2,1.6),(0.5,0.5,0.5), (1,2))
In [14]: diags=[np.diag(group) for group in x]
In [15]: diags
Out[15]:
[array([[1.2, 0. ],
[0. , 1.6]]),
array([[0.5, 0. , 0. ],
[0. , 0.5, 0. ],
[0. , 0. , 0.5]]),
array([[1, 0],
[0, 2]])]
In [45]: functools.reduce(row_by_row_concatenation_of_two_arrays, diags)
Out[45]:
array([[1.2, 0. , 0.5, 0. , 0. , 1. , 0. ],
[1.2, 0. , 0.5, 0. , 0. , 0. , 2. ],
[1.2, 0. , 0. , 0.5, 0. , 1. , 0. ],
[1.2, 0. , 0. , 0.5, 0. , 0. , 2. ],
[1.2, 0. , 0. , 0. , 0.5, 1. , 0. ],
[1.2, 0. , 0. , 0. , 0.5, 0. , 2. ],
[0. , 1.6, 0.5, 0. , 0. , 1. , 0. ],
[0. , 1.6, 0.5, 0. , 0. , 0. , 2. ],
[0. , 1.6, 0. , 0.5, 0. , 1. , 0. ],
[0. , 1.6, 0. , 0.5, 0. , 0. , 2. ],
[0. , 1.6, 0. , 0. , 0.5, 1. , 0. ],
[0. , 1.6, 0. , 0. , 0.5, 0. , 2. ]])
我猜对于广义情况,有一种更快的方法可以做到这一点,但这符合我的目的。