【问题标题】:python filling an list with random amount [lb,ub]python用随机量[lb,ub]填充列表
【发布时间】:2018-03-11 07:41:22
【问题描述】:

我想在 python 3.6 中用 LB 和 UB 之间的随机变量填充一些大小为 N 的列表。

你能指导我吗?

【问题讨论】:

    标签: python list random


    【解决方案1】:

    使用random.randint

    >>> 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]
    

    【讨论】:

      【解决方案2】:

      查看randomnumpy.random(我认为第二个更好,但需要安装numpy)。

      要使用的具体函数取决于您想要哪些数字,以及您希望它们如何分配: 如果你想要均匀分布的整数,你可以使用random.randint(LB, UB)。如果你想要浮动,你可以使用random.uniform(LB, UB)。例如,您还可以有正态分布的数字。

      numpy 的 random 使它更容易,因为它可以返回一个列表。例如:

      numpy.random.randint(LB, UB, N)
      

      【讨论】:

        猜你喜欢
        • 2021-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多