需要编写一个Python脚本,根据5个参数创建一个随机整数矩阵:
函数random.random_integers一直没有提供步骤选项。我似乎无法将其与范围功能结合在一起。
以下是一个例子:
此:
大小3x4,范围22-37,步骤2
创建此:
[[26 22 32 28]
[24 30 26 22]
[36 34 22 36]]
答案 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]])
>>>