创建具有唯一行和列的数组

时间:2015-04-21 23:43:13

标签: python arrays list matrix

如何在python中创建一个具有独特行和列的数组?

  [1, 2, 3, 4] 

  [2, 3, 4, 1]

  [4, 1, 2, 3]

  [3, 4, 1, 2]

2 个答案:

答案 0 :(得分:2)

from itertools import permutations
from random import choice

>>> a = list(permutations([1,2,3,4], 4))
>>> total = [choice(a) for i in range(4)]
>>> total
[(3, 4, 1, 2), (4, 1, 2, 3), (2, 1, 4, 3), (1, 2, 3, 4)]
>>> print(*(' '.join(map(str, item)) for item in total), sep='\n')
3 4 1 2
4 1 2 3
2 1 4 3
1 2 3 4

答案 1 :(得分:1)

使用itertools.permutations方法可以轻松实现这一点:

import itertools
a = [1,2,3,4]
list(itertools.permutations(a))
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]