使用不带 NUMPY 的随机数创建二维数组 (Python)

tja*_*ner 2 python arrays random numbers

如何在不使用 NumPy (Python) 的情况下创建带有随机数的二维数组

yat*_*atu 5

您可以使用该random模块并使用列表理解填充嵌套列表

import random

low = 0
high = 10
cols = 10
rows = 5

[random.choices(range(low,high), k=cols) for _ in range(rows)]

[[5, 7, 1, 0, 6, 5, 9, 2, 5, 6],
 [9, 2, 3, 0, 6, 7, 0, 6, 6, 3],
 [2, 7, 9, 2, 4, 5, 5, 9, 9, 4],
 [2, 6, 7, 8, 5, 1, 4, 4, 4, 4],
 [9, 2, 8, 4, 5, 2, 0, 1, 2, 1]]
Run Code Online (Sandbox Code Playgroud)

对于嵌套的浮点数列表,您可以将每个浮点数映射rangefloat

choices = list(map(float, range(low,high)))
[random.choices(choices , k=cols) for _ in range(rows)]

[[0.0, 3.0, 9.0, 1.0, 5.0, 3.0, 7.0, 4.0, 2.0, 4.0],
 [5.0, 8.0, 7.0, 7.0, 7.0, 2.0, 9.0, 8.0, 2.0, 6.0],
 [3.0, 3.0, 1.0, 9.0, 2.0, 8.0, 7.0, 2.0, 9.0, 7.0],
 [7.0, 8.0, 1.0, 2.0, 0.0, 6.0, 7.0, 6.0, 0.0, 9.0],
 [3.0, 3.0, 3.0, 1.0, 7.0, 8.0, 3.0, 9.0, 2.0, 8.0]]
Run Code Online (Sandbox Code Playgroud)