在Python中创建具有所需步长的随机整数矩阵

时间:2015-02-25 04:33:08

标签: python numpy matrix random range

需要编写一个Python脚本,根据5个参数创建一个随机整数矩阵:

  1. 行数
  2. 列数
  3. 随机值范围内的最低值
  4. 随机值范围内的最高值
  5. 范围内的步数值(例如:低= 50,高= 100,步长= 5 ......可用随机值包括50,55,60,65 ......等)
  6. 函数random.random_integers一直没有提供步骤选项。我似乎无法将其与范围功能结合在一起。

    以下是一个例子:

    此:
    大小3x4,范围22-37,步骤2

    创建此:

    [[26 22 32 28]  
     [24 30 26 22]  
     [36 34 22 36]]
    

3 个答案:

答案 0 :(得分:3)

或者你可以使用numpy。

import numpy as np

rows  = 3
cols = 4
low = 22
high = 37
step = 2

matrix = np.random.choice([x for x in xrange(low,high,step)],rows*cols)
matrix.resize(rows,cols)

print(matrix)

>>> [[36 22 26 30]
     [22 26 36 34]
     [30 32 28 36]]
>>> 

答案 1 :(得分:2)

使用randrange

import random
rows = 3
columns = 4
[[random.randrange(22, 37, 2) for x in range(columns)] for y in range(rows)]

答案 2 :(得分:1)

没有步骤的替代方式。

>>> import numpy as np
>>> rows = 3
>>> cols = 4
>>> a = np.matrix(np.random.randint(22,37, size=(rows, cols)))
>>>
>>> a
matrix([[33, 25, 35, 32],
        [31, 23, 32, 35],
        [23, 25, 32, 34]])
>>>