我是编程和python的新手。我正在尝试创建一个在一定范围内具有随机数的matrix(6,6)。每个数字必须是两次。我应该使用矩阵,多维数组还是列表列表?我想知道最简单的方法是什么。
这就是我现在拥有的:
rows = 6
columns = 6
range(0, 18)
matrix = [[0 for x in range(rows)] for y in range(columns)]
# Loop into matrix to fill with random numbers withing the range property.
# Matrix should have the same number twice.
for row in matrix:
print(row)
答案 0 :(得分:3)
假设您要查找整数,就这么简单:
import numpy as np
import random
number_sample = list(range(18))*2 #Get two times numbers from 0 to 17
random.shuffle(number_sample) #Shuffle said numbers
np.array(number_sample).reshape(6,6) #Reshape into matrix
array([[ 1, 0, 5, 1, 8, 15],
[ 9, 3, 15, 17, 0, 14],
[ 7, 9, 11, 7, 16, 13],
[ 4, 10, 8, 12, 5, 6],
[ 6, 11, 4, 14, 3, 13],
[10, 16, 2, 17, 2, 12]])
编辑:更改的答案以反映您的问题中的变化
答案 1 :(得分:3)
您可以:
2 * list(range(18))
的两倍仅使用标准库,结果将是满足您要求的矩阵。
类似这样的东西:
import random
nums = 2 * list(range(18))
random.shuffle(nums)
matrix = [nums[i:i+6] for i in range(0, 36, 6)]