例如,如果有5个数字1,2,3,4,5
我想要一个随机的结果
[[ 2, 3, 1, 4, 5]
[ 5, 1, 2, 3, 4]
[ 3, 2, 4, 5, 1]
[ 1, 4, 5, 2, 3]
[ 4, 5, 3, 1, 2]]
Run Code Online (Sandbox Code Playgroud)
确保其行和列中的每个数字都是唯一的.
有没有一种有效的方法来做到这一点?
我尝试使用while循环为每次迭代生成一行,但似乎效率不高.
import numpy as np
numbers = list(range(1,6))
result = np.zeros((5,5), dtype='int32')
row_index = 0
while row_index < 5:
np.random.shuffle(numbers)
for column_index, number in enumerate(numbers):
if number in result[:, column_index]:
break
else:
result[row_index, :] = numbers
row_index += 1
Run Code Online (Sandbox Code Playgroud)