如何在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
当前回答
from random import randint
x = [randint(0, 9) for p in range(0, 10)]
这将生成范围为0到9(含0到9)的10个伪随机整数。
其他回答
生成0到9之间的随机整数。
import numpy
X = numpy.random.randint(0, 10, size=10)
print(X)
输出:
[4 8 0 4 9 6 9 9 0 7]
>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1
要获得十个样本的列表:
>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]
您需要随机python模块,它是标准库的一部分。使用代码。。。
from random import randint
num1= randint(0,9)
这将将变量num1设置为介于0和9之间的随机数(包括0和9)。
对于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”或“^!~=-><”等字符要更改要从中提取的字符池,请更改范围以更改生成的字符数。
如果要使用numpy,请使用以下命令:
import numpy as np
print(np.random.randint(0,10))