# 生成0到9之间的随机整数

`0`

` `from random import randint print(randint(0, 9))` `

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

` `random.randint(a, b)` `

` `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)` `
` `from random import randint x=[randint(0,9) for p in range(0,9)]` `

`secrets`模块在Python 3.6中是新的。 这比密码学或安全用途的`random`模块更好。

` `from secrets import randbelow print(randbelow(10))` `

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

` `>>> import random >>> values = list(range(10)) >>> random.choice(values) 5` `

`choice`也适用于来自不连续样本的一个项目：

` `>>> values = [1, 2, 3, 5, 7, 10] >>> random.choice(values) 7` `

` `>>> import secrets >>> values = list(range(10)) >>> secrets.choice(values) 2` `

` `import numpy as np print(np.random.randint(0,10))` `

select数组的大小（在这个例子中，我select了大小为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]])` `
` `>>> 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]` `

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

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

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

` `from random import randint numberStartRange = 1 numberEndRange = 9 randomNumber = randint(numberStartRange, numberEndRange) print(randomNumber)` `

` `import random N = 5 [random.randint(0, 9) for _ in range(N)] # [9, 7, 0, 7, 3] [random.choice(range(10)) for _ in range(N)] # [8, 3, 6, 8, 7]` `

`random.sample`从一个总体中返回`k`唯一的select（无replace）： 2

` `random.sample(range(10), k=N) # [4, 5, 1, 2, 3]` `

` `random.choices(range(10), k=N) # [3, 2, 0, 8, 2]` `

1 @John Lawrence Aspden @SThamham @SiddTheKid @ user14372 @zangw等人。

2 @prashanth提到这个模块显示一个整数。

` `str_Key = "" str_RandomKey = "" for int_I in range(128): str_Key = random.choice('0123456789') str_RandomKey = str_RandomKey + str_Key` `