如何在Python中生成介于0和9(含)之间的随机整数?

例如,0、1、2、3、4、5、6、7、8、9


当前回答

选择阵列的大小(在本例中,我选择的大小为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'

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

尝试random.randrange:

from random import randrange
print(randrange(10))

对于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”或“^!~=-><”等字符要更改要从中提取的字符池,请更改范围以更改生成的字符数。

random.sample是另一个可以使用的

import random
n = 1 # specify the no. of numbers
num = random.sample(range(10),  n)
num[0] # is the required number

通过random.shuffle尝试

>>> import random
>>> nums = range(10)
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]