如何在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个伪随机整数。

其他回答

试试看:

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)

尝试random.randrange:

from random import randrange
print(randrange(10))

选择阵列的大小(在本例中,我选择的大小为20)。然后,使用以下方法:

import numpy as np   
np.random.randint(10, size=(1, 20))

您可以期望看到以下形式的输出(每次运行时都会返回不同的随机整数;因此,您可以期望输出数组中的整数与下面给出的示例不同)。

array([[1, 6, 1, 2, 8, 6, 3, 3, 2, 5, 6, 5, 0, 9, 5, 6, 4, 5, 9, 3]])

从随机模块的文档页面:

警告:此模块的伪随机生成器不应用于安全目的。如果需要,请使用os.urantom()或SystemRandom需要密码安全的伪随机数发生器。

Python 2.4中引入的random.SystemRandom被认为是加密安全的。它在Python 3.7.1中仍然可用,在编写时是最新的。

>>> import string
>>> string.digits
'0123456789'
>>> import random
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'1'
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'5'

除了字符串数字,还可以对其他一些答案使用范围,也许还可以理解。根据您的需要进行混合和搭配。

您需要随机python模块,它是标准库的一部分。使用代码。。。

from random import randint

num1= randint(0,9)

这将将变量num1设置为介于0和9之间的随机数(包括0和9)。