所以我有
mat = [[0, 5, 3, 1],
[2, 0, 4, 2],
[3, 4, 0, 3],
[2, 3, 5, 0]]
我想做一个这样的分区矩阵
ex = [[mat_ii, mat_ij],
[mat_ji, mat_jj]]
随机选择 i 和 j。
我试过了
ordDet = [0, 1, 2, 3]
random.shuffle(ordDet)
submat = [
[mat[ordDet[0]][ordDet[0]], mat[ordDet[0]][ordDet[1]]],
[mat[ordDet[1]][ordDet[0]], mat[ordDet[1]][ordDet[1]]]
]
但是我不能为大规模数据手动执行此操作,有没有办法使用列表理解来执行此操作?
import random
mat = [[0, 5, 3, 1],
[2, 0, 4, 2],
[3, 4, 0, 3],
[2, 3, 5, 0]]
n=len(mat) # rows
m=len(mat[0]) # columns
rows=[i for i in range(n)]
columns=[i for i in range(m)]
random.shuffle(rows)
random.shuffle(columns)
submat = [
[mat[random.choice(rows)][random.choice(columns)], mat[random.choice(rows)][random.choice(columns)]],
[mat[random.choice(rows)][random.choice(columns)], mat[random.choice(rows)][random.choice(columns)]]
]
我假设
submat
矩阵总是2x2.
这对你有用吗? 只需为子矩阵定义“SUBMAT_WIDTH”
import random
mat = [[0, 5, 3, 1],
[2, 0, 4, 2],
[3, 4, 0, 3],
[2, 3, 5, 0]]
#define submat width
SUBMAT_WIDTH = 3
#create random list
randomindex=[x for x in range(len(mat))]
random.shuffle(randomindex)
#slice randomindex
randomindex = randomindex[:SUBMAT_WIDTH]
sub_mat = [[mat[x][y] for y in randomindex ] for x in randomindex]