用范围内的随机数填充矩阵?

时间:2019-10-14 18:43:16

标签: python python-3.x list

我是编程和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)

2 个答案:

答案 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)

您可以:

  • 生成一个由36个数字组成的列表,每个数字的0-17值是2 * list(range(18))的两倍
  • 随机播放数字列表
  • 将列表切成等于6的大块

仅使用标准库,结果将是满足您要求的矩阵。

类似这样的东西:

import random

nums = 2 * list(range(18))
random.shuffle(nums)
matrix = [nums[i:i+6] for i in range(0, 36, 6)]