如何在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
当前回答
random.sample是另一个可以使用的
import random
n = 1 # specify the no. of numbers
num = random.sample(range(10), n)
num[0] # is the required number
其他回答
对于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函数
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中删除并返回任意值。
尝试random.randit:
import random
print(random.randint(0, 9))
文档状态:
随机随机(a,b)返回一个随机整数N,使得a<=N<=b。
选择阵列的大小(在本例中,我选择的大小为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]])
这更多是一种数学方法,但它在100%的时间内都有效:
假设您想使用random()函数生成a和b之间的数字。要实现这一点,只需执行以下操作:
num=(b-a)*随机随机()+a;
当然,你可以生成更多的数字。