以特定的块状顺序将列表转换为二维数组

Transform list into 2D array in specific block-ish order

我正在努力解决将元素列表转换为 2D 数组的问题,但在此图像上显示的是特定的块状顺序。块始终为 NxN 形状。

任何python代码或伪代码都会有所帮助:)

您可以通过以下方式重塑每个子列表:

https://numpy.org/doc/stable/reference/generated/numpy.reshape.html

然后将 everething 合并回 NxN 矩阵

只使用 Python 而没有 numpy 我做了这样的东西 - 但很难解释它。

data = list(range(1, 55))

for z in range(0, 54, 27):
    for y in range(0, 9, 3):
        for x in range(z+y, z+27, 9):
            temp = data[x:x+3] 
            print(temp, end=',')
        print()

结果:

[1, 2, 3],[10, 11, 12],[19, 20, 21],
[4, 5, 6],[13, 14, 15],[22, 23, 24],
[7, 8, 9],[16, 17, 18],[25, 26, 27],
[28, 29, 30],[37, 38, 39],[46, 47, 48],
[31, 32, 33],[40, 41, 42],[49, 50, 51],
[34, 35, 36],[43, 44, 45],[52, 53, 54],

您可以将其保存在变量中,而不是 print()

data = list(range(1, 55))

result = []
for z in range(0, 54, 27):
    for y in range(0, 9, 3):
        row = []
        for x in range(z+y, z+27, 9):
            temp = data[x:x+3] 
            row += temp
        result.append(row)
        
for row in result:
    print(row) 

获得:

[1, 2, 3, 10, 11, 12, 19, 20, 21]
[4, 5, 6, 13, 14, 15, 22, 23, 24]
[7, 8, 9, 16, 17, 18, 25, 26, 27]
[28, 29, 30, 37, 38, 39, 46, 47, 48]
[31, 32, 33, 40, 41, 42, 49, 50, 51]
[34, 35, 36, 43, 44, 45, 52, 53, 54]

或者您可以将 result 转换为 numpy.array

import numpy as np
result = np.array(result)
print(result) 

获得:

[[ 1  2  3 10 11 12 19 20 21]
 [ 4  5  6 13 14 15 22 23 24]
 [ 7  8  9 16 17 18 25 26 27]
 [28 29 30 37 38 39 46 47 48]
 [31 32 33 40 41 42 49 50 51]
 [34 35 36 43 44 45 52 53 54]]

与常数值相同。它可以对不同的列表更有用

LIST_SIZE = 54
ROW_SIZE  = LIST_SIZE//2

SUBLIST_SIZE  = 9
SUBARRAY_SIZE = 3

data = list(range(1, LIST_SIZE+1))

result = []
for z in range(0, LIST_SIZE, ROW_SIZE):
    for y in range(0, SUBLIST_SIZE, SUBARRAY_SIZE):
        row = []
        for x in range(z+y, z+ROW_SIZE, SUBLIST_SIZE):
           temp = data[x:x+SUBARRAY_SIZE]
           row += temp
           print(temp, end=',')
        result.append(row)
        print()

print('---')

for row in result:
    print(row)        

print('---')

import numpy as np
result = np.array(result)
print(result)        

结果:

[1, 2, 3],[10, 11, 12],[19, 20, 21],
[4, 5, 6],[13, 14, 15],[22, 23, 24],
[7, 8, 9],[16, 17, 18],[25, 26, 27],
[28, 29, 30],[37, 38, 39],[46, 47, 48],
[31, 32, 33],[40, 41, 42],[49, 50, 51],
[34, 35, 36],[43, 44, 45],[52, 53, 54],
---
[1, 2, 3, 10, 11, 12, 19, 20, 21]
[4, 5, 6, 13, 14, 15, 22, 23, 24]
[7, 8, 9, 16, 17, 18, 25, 26, 27]
[28, 29, 30, 37, 38, 39, 46, 47, 48]
[31, 32, 33, 40, 41, 42, 49, 50, 51]
[34, 35, 36, 43, 44, 45, 52, 53, 54]
---
[[ 1  2  3 10 11 12 19 20 21]
 [ 4  5  6 13 14 15 22 23 24]
 [ 7  8  9 16 17 18 25 26 27]
 [28 29 30 37 38 39 46 47 48]
 [31 32 33 40 41 42 49 50 51]
 [34 35 36 43 44 45 52 53 54]]