Python中对称数组的置换

时间:2018-09-03 20:17:30

标签: python numpy permutation

我想对这个对称矩阵进行排列,如果我们将第二列移到第三列,那么第二行也应该移到第三行。

array([[ 0.        ,  0.06377803,  0.1157737 ,  0.19542195],
       [ 0.06377803,  0.        ,  0.14754803,  0.23185761],
       [ 0.1157737 ,  0.14754803,  0.        ,  0.0843134 ],
       [ 0.19542195,  0.23185761,  0.0843134 ,  0.        ]])

这是用于列表排列的代码:

import numpy as np
x=[]
def perm(a, k=0):

    if k == len(a):
        x.extend(a)
#        print (a )


    else:
      for i in range(k, len(a)):
         a[k], a[i] = a[i] ,a[k]
         perm(a, k+1)
         a[k], a[i] = a[i], a[k]

perm([0,1,2,3])
a=np.asarray(x).reshape((24,4))
print(a)

输出:

[[0 1 2 3]
 [0 1 3 2]
 [0 2 1 3]
 [0 2 3 1]
 [0 3 2 1]
 [0 3 1 2]
 [1 0 2 3]
 [1 0 3 2]
 [1 2 0 3]
 [1 2 3 0]
 [1 3 2 0]
 [1 3 0 2]
 [2 1 0 3]
 [2 1 3 0]
 [2 0 1 3]
 [2 0 3 1]
 [2 3 0 1]
 [2 3 1 0]
 [3 1 2 0]
 [3 1 0 2]
 [3 2 1 0]
 [3 2 0 1]
 [3 0 2 1]
 [3 0 1 2]]

但是我想为上述数组设置4 * 4的排列。为了简单起见,如果我们有一个3 * 3的数组,我们想要下面这样的东西:K!= 6,但是当k = 4时,我们必须得到k !!这是24个排列

enter image description here

1 个答案:

答案 0 :(得分:3)

import numpy as np
from itertools import permutations

n = 3
a = np.arange(n**2).reshape(n, n)

for perm in permutations(range(a.shape[0])):
    b = np.zeros_like(a)
    b[:, :] = a[perm, :]
    b[:, :] = b[:, perm]
    print(b)

给出以下6个矩阵:

[[0 1 2]
 [3 4 5]
 [6 7 8]]
[[0 2 1]
 [6 8 7]
 [3 5 4]]
[[4 3 5]
 [1 0 2]
 [7 6 8]]
[[4 5 3]
 [7 8 6]
 [1 2 0]]
[[8 6 7]
 [2 0 1]
 [5 3 4]]
[[8 7 6]
 [5 4 3]
 [2 1 0]]

这是问题吗?