【发布时间】:2018-03-11 07:41:22
【问题描述】:
我想在 python 3.6 中用 LB 和 UB 之间的随机变量填充一些大小为 N 的列表。
你能指导我吗?
【问题讨论】:
我想在 python 3.6 中用 LB 和 UB 之间的随机变量填充一些大小为 N 的列表。
你能指导我吗?
【问题讨论】:
>>> import random
>>> N = 5 # count
>>> LB = 0 # lower bound
>>> UB = 10 # upper bound
>>> [random.randint(LB, UB) for _ in range(N)]
[6, 6, 5, 3, 2]
【讨论】:
查看random 或numpy.random(我认为第二个更好,但需要安装numpy)。
要使用的具体函数取决于您想要哪些数字,以及您希望它们如何分配:
如果你想要均匀分布的整数,你可以使用random.randint(LB, UB)。如果你想要浮动,你可以使用random.uniform(LB, UB)。例如,您还可以有正态分布的数字。
numpy 的 random 使它更容易,因为它可以返回一个列表。例如:
numpy.random.randint(LB, UB, N)
【讨论】: