如何在python中创建一个具有独特行和列的数组?
[1, 2, 3, 4]
[2, 3, 4, 1]
[4, 1, 2, 3]
[3, 4, 1, 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)]