MWE:假设我有12个2D阵列。我想使用循环将它们合并到一些固定大小。下面的代码给出了我想得到X的结果。这里我连接了3个2D数组,但是如果我想根据我的选择使用循环来修复这个大小,我该怎么办呢?
import numpy as np
a1 = np.array([[0, 12, 3], [5, 8, 9]])
a2 = np.array([[2, 13, 3], [5, 9, 9]])
a3 = np.array([[0, 24, 4], [6, 10, 9]])
a4 = np.array([[1, 55, 6], [4, 5, 19]])
a5 = np.array([[1, 56, 6], [4, 01, 9]])
a6 = np.array([[1, 57, 6], [4, 20, 9]])
a7 = np.array([[1, 58, 6], [4, 30, 9]])
a8 = np.array([[1, 59, 6], [4, 40, 9]])
a9 = np.array([[1, 51, 6], [4, 60, 9]])
a10 = np.array([[1, 34, 6], [4, 60, 9]])
a11 = np.array([[1, 51, 62], [4, 30, 9]])
a12 = np.array([[1, 1, 6], [4, 7, 9]])
M=[a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12]
d1 = np.concatenate((a1,a2,a3), 1)
d2 = np.concatenate((a4,a5,a6), 1)
d3 = np.concatenate((a7,a8,a9), 1)
d4 = np.concatenate((a10,a11,a12), 1)
X=[d1,d2,d3,d4]
答案 0 :(得分:2)
你的问题有点不清楚 我假设您想要将连续的2D数组(例如d1,d2,..)的数量变为可变,并且使用循环在代码中执行相同的操作。
你可以这样做:
这将得到与您的代码相同的结果,您可以更改变量chosenSize
以获得不同的结果。
a1 = np.array([[0, 12, 3], [5, 8, 9]])
a2 = np.array([[2, 13, 3], [5, 9, 9]])
a3 = np.array([[0, 24, 4], [6, 10, 9]])
a4 = np.array([[1, 55, 6], [4, 5, 19]])
a5 = np.array([[1, 56, 6], [4, 1, 9]])
a6 = np.array([[1, 57, 6], [4, 20, 9]])
a7 = np.array([[1, 58, 6], [4, 30, 9]])
a8 = np.array([[1, 59, 6], [4, 40, 9]])
a9 = np.array([[1, 51, 6], [4, 60, 9]])
a10 = np.array([[1, 34, 6], [4, 60, 9]])
a11 = np.array([[1, 51, 62], [4, 30, 9]])
a12 = np.array([[1, 1, 6], [4, 7, 9]])
M = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12]
d1 = [] # will be used to concatenate
X = []
chosenSize = 3 # chosen size
numberOfIterations = M.__len__()//chosenSize
for i in range(0, numberOfIterations):
for j in range(0, chosenSize):
d1.append(M[j + chosenSize * i])
d1 = np.concatenate(d1, 1)
X.append(d1)
d1 = []
print(X)