如何在Python中生成介于0和9(含)之间的随机整数?
例如,0、1、2、3、4、5、6、7、8、9
如何在Python中生成介于0和9(含)之间的随机整数?
例如,0、1、2、3、4、5、6、7、8、9
当前回答
如果要使用numpy,请使用以下命令:
import numpy as np
print(np.random.randint(0,10))
其他回答
OpenTURNS不仅可以模拟随机整数,还可以使用UserDefined定义的类定义关联的分布。
以下模拟了分布的12个结果。
import openturns as ot
points = [[i] for i in range(10)]
distribution = ot.UserDefined(points) # By default, with equal weights.
for i in range(12):
x = distribution.getRealization()
print(i,x)
这将打印:
0 [8]
1 [7]
2 [4]
3 [7]
4 [3]
5 [3]
6 [2]
7 [9]
8 [0]
9 [5]
10 [9]
11 [6]
括号在那里,因为x是一维中的一个点。在对getSample的一次调用中生成12个结果会更容易:
sample = distribution.getSample(12)
将产生:
>>> print(sample)
[ v0 ]
0 : [ 3 ]
1 : [ 9 ]
2 : [ 6 ]
3 : [ 3 ]
4 : [ 2 ]
5 : [ 6 ]
6 : [ 9 ]
7 : [ 5 ]
8 : [ 9 ]
9 : [ 5 ]
10 : [ 3 ]
11 : [ 2 ]
有关此主题的更多详细信息,请参见:http://openturns.github.io/openturns/master/user_manual/_generated/openturns.UserDefined.html
试试看:
from random import randrange, uniform
# randrange gives you an integral value
irand = randrange(0, 10)
# uniform gives you a floating-point value
frand = uniform(0, 10)
最好的方法是使用import Random函数
import random
print(random.sample(range(10), 10))
或没有任何库导入:
n={}
for i in range(10):
n[i]=i
for p in range(10):
print(n.popitem()[1])
这里popitems从字典n中删除并返回任意值。
这更多是一种数学方法,但它在100%的时间内都有效:
假设您想使用random()函数生成a和b之间的数字。要实现这一点,只需执行以下操作:
num=(b-a)*随机随机()+a;
当然,你可以生成更多的数字。
对于Python 3.6,我有更好的运气
str_Key = ""
str_RandomKey = ""
for int_I in range(128):
str_Key = random.choice('0123456789')
str_RandomKey = str_RandomKey + str_Key
只需添加“ABCD”和“ABCD”或“^!~=-><”等字符要更改要从中提取的字符池,请更改范围以更改生成的字符数。