【问题标题】:Create matrix of random integers in Python with a desired step size [closed]在 Python 中创建具有所需步长的随机整数矩阵 [关闭]
【发布时间】:2015-04-26 23:35:39
【问题描述】:
需要编写一个 Python 脚本,根据 5 个参数创建一个随机整数矩阵:
- 行数
- 列数
- 随机值范围内的最小值
- 随机值范围内的最大值
- 范围内的步长值(例如:low=50、high=100、step=5...可用的随机值包括 50、55、60、65...等)
函数 random.random_integers 一直没有给出一个步骤选项。我似乎无法将它与 range 函数放在一起。
这是一个例子:
这个:
尺寸 3x4,范围 22-37,第 2 步
创建这个:
[[26 22 32 28]
[24 30 26 22]
[36 34 22 36]]
【问题讨论】:
标签:
python
numpy
matrix
random
range
【解决方案1】:
使用 randrange
import random
rows = 3
columns = 4
[[random.randrange(22, 37, 2) for x in range(columns)] for y in range(rows)]
【解决方案2】:
没有步骤的替代方式。
>>> 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]])
>>>
【解决方案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]]
>>>