我想将我的10x10阵列分成小的2x2阵列。我试图使用 itertools.product(),但没有正常工作。另外,我不会使用numpy。这是代码:
ar = [[1,2,3,4],
[5,6,7,8,],
[9,10,11,12],
[13,14,15,16]]
l=[]
for i in ar:
for j in i:
l+=j
ans = []
for i in range(0,len(l) + 1, 2):
ans.append(l[i:i+2])
ans.append(l[i+4:i+6])
我的期望是:[[1,5,2,6],[3,7,4,8],[9,13,10,14],[11,15,12,16]]
我得到了什么:[[1, 2], [5, 6], [3, 4], [7, 8], [5, 6], [9, 10], [7, 8], [11, 12], [9, 10], [13, 14], [11, 12], [15, 16], [13, 14], [], [15, 16], [], [], []]
答案 0 :(得分:0)
您可以使用
for i, j in itertools.product(range(0,nrows,h), range(0,ncols,w))
迭代每个小数组的起始索引,并使用
for dj, di in itertools.product(range(w), range(h))
迭代小数组中的元素。例如,
import itertools as IT
ar = [[1,2,3,4],
[5,6,7,8,],
[9,10,11,12],
[13,14,15,16]]
nrows, ncols = len(ar), len(ar[0])
h, w = 2, 2
print([[ar[i+di][j+dj] for dj, di in IT.product(range(w), range(h))]
for i, j in IT.product(range(0,nrows,h), range(0,ncols,w))])
打印
[[1, 5, 2, 6], [3, 7, 4, 8], [9, 13, 10, 14], [11, 15, 12, 16]]
如果您希望用for循环替换list comprehensions,则等效于
ans = []
for i, j in IT.product(range(0,nrows,h), range(0,ncols,w)):
small_array = []
for dj, di in IT.product(range(w), range(h)):
small_array.append(ar[i+di][j+dj])
ans.append(small_array)
print(ans)