在Python中,如何生成数组的排列,其中每个列和行只有一个元素?

时间:2013-10-28 16:48:24

标签: python arrays algorithm permutation

例如:

假设你有以下数组:

[1,2,3]
[4,5,6]
[7,8,9]

并且您想要生成此数组:

[1,5,9]
[1,6,8]
[4,2,9]
[4,8,3]
[7,2,6]
[7,5,3]

1 个答案:

答案 0 :(得分:18)

import itertools

A=[[1,2,3],
[4,5,6],
[7,8,9]]

for P in itertools.permutations(range(len(A))):
    print [A[p][i] for i,p in enumerate(P)]

打印:

[1, 5, 9]
[1, 8, 6]
[4, 2, 9]
[4, 8, 3]
[7, 2, 6]
[7, 5, 3]