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

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


当前回答

这更多是一种数学方法,但它在100%的时间内都有效:

假设您想使用random()函数生成a和b之间的数字。要实现这一点,只需执行以下操作:

num=(b-a)*随机随机()+a;

当然,你可以生成更多的数字。

其他回答

尝试random.randit:

import random
print(random.randint(0, 9))

文档状态:

随机随机(a,b)返回一个随机整数N,使得a<=N<=b。

如果要使用numpy,请使用以下命令:

import numpy as np
print(np.random.randint(0,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”或“^!~=-><”等字符要更改要从中提取的字符池,请更改范围以更改生成的字符数。

>>> 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]

从随机模块的文档页面:

警告:此模块的伪随机生成器不应用于安全目的。如果需要,请使用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'

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