如何在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
当前回答
选择阵列的大小(在本例中,我选择的大小为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]])
其他回答
在连续数字的情况下,randint或randrange可能是最好的选择,但如果序列中有几个不同的值(即列表),也可以使用choice:
>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5
该选项也适用于非连续样本中的一项:
>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7
如果您需要“加密性强”,python 3.6和更新版本中还有一个secrets.choice:
>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2
通过random.shuffle尝试
>>> import random
>>> nums = range(10)
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]
选择阵列的大小(在本例中,我选择的大小为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]])
from random import randint
x = [randint(0, 9) for p in range(0, 10)]
这将生成范围为0到9(含0到9)的10个伪随机整数。
random.sample是另一个可以使用的
import random
n = 1 # specify the no. of numbers
num = random.sample(range(10), n)
num[0] # is the required number