让我们只使用 numpy 内置插件来处理这个问题:它会比 for 循环更快。
import numpy as np
# N = 3 dummy arrays for the example
a = np.zeros([4, 5])
b = 10 * np.ones([4, 5])
c = 2 * b
arr = np.array([a, b, c]) # this is a 3D array containing your N arrays
N = arr.shape[0]
idx = np.random.choice(range(N), 4 * 5) # 4 and 5 are the common dimensions of your N arrays
# treating this a a 1D problem, but treating as 2D is possible too.
arr.reshape(N, 20)[idx.ravel(), np.arange(20)].reshape(4, 5)
如果你想有不同的概率,你可以将参数 p 传递给 np.random.choice (一个形状为 (N,) 的数组,其总和必须为 1):
idx_p = np.random.choice(range(n_arr), 4 * 5, p = [0.1, 0.2, 0.7])
arr.reshape(n_arr, 20)[idx_p.ravel(), np.arange(20)].reshape(4, 5)
这给出:
# first result:
array([[ 0., 0., 0., 20., 10.],
[ 20., 0., 20., 0., 10.],
[ 0., 10., 0., 10., 0.],
[ 10., 20., 10., 0., 10.]])
# second result with many 20, a few 10 and fewer 0:
array([[ 10., 0., 20., 20., 20.],
[ 20., 0., 20., 20., 20.],
[ 10., 20., 20., 20., 10.],
[ 20., 10., 20., 20., 20.]])