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

2024-03-29 10:37:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程和python的新手。我试图创建一个矩阵(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)

Tags: columnsthe方法in列表for编程range
2条回答

你可以:

  • 生成一个包含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)]

假设你在寻找整数,就这么简单:

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]])

编辑:更改答案以反映问题的更改

相关问题 更多 >