繁体   English   中英

如何在Python中生成特定的随机数?

[英]How to generate specific random numbers in Python?

我需要使用Python生成特定随机数列表的帮助。

我知道如何生成这样的随机数列表

import random
number = random.sample(xrange(1,10), 3)

这将生成1到10之间的3个随机数。(示例)

[7, 6, 1]

我要实现的是生成具有重复值的像这样的随机数列表(示例)

[10000, 30000, 20000, 60000, 100, 3000, 3000, 100, ...]

但是像这样使用上面的脚本

import random
number = random.sample(xrange(10000,100000), 4)

产生以下结果(示例)

[12489, 43177, 51867, 68831]

有可能做我想在这里实现的目标吗? 谢谢你的回答。

看起来像您的例子

import random
n1 = random.sample(xrange(1,10), 4)
n2 = random.sample(xrange(2,6), 4)
numbers = [n1i * 10**n2i for n1i, n2i in zip(n1, n2)]

样本输出:

[800000, 7000, 200, 30000]

如果要重复:

random.choices(numbers, k=6)

样本输出:

[800000, 7000, 800000, 800000, 7000, 200]

您是否正在寻找四舍五入的随机数?

import random
numbers = [1000*x for x in random.sample(xrange(1,100), 4)]

尝试这个:

import numpy as np
array1 = np.random.randint(8, size=10)
array2 = np.random.randint(6, size=10)
array3 = (np.power(10, array2)) * array1

数组“ array1”,“ array2”和“ array3”是(示例):

array1 = [2 3 6 7 5 1 1 5 5 7]
array2 = [2 4 1 3 4 5 2 2 4 2]
array3 = [200 30000 60 7000 50000 100000 100 500 50000 700]

array3是您想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM