Skip to main content
 首页 » 编程设计

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

2025年05月04日14artech

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

请您参考如下方法:

你可以:

  • 生成一个包含 36 个数字的列表,每个数字的值为 0-17 两次 2 * list(range(18))
  • 打乱数字列表
  • 将列表切成相等的 6 block

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

像这样:

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