如何在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
当前回答
对于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”或“^!~=-><”等字符要更改要从中提取的字符池,请更改范围以更改生成的字符数。
其他回答
如果要使用numpy,请使用以下命令:
import numpy as np
print(np.random.randint(0,10))
from random import randint
x = [randint(0, 9) for p in range(0, 10)]
这将生成范围为0到9(含0到9)的10个伪随机整数。
从随机模块的文档页面:
警告:此模块的伪随机生成器不应用于安全目的。如果需要,请使用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'
除了字符串数字,还可以对其他一些答案使用范围,也许还可以理解。根据您的需要进行混合和搭配。
虽然许多帖子都演示了如何获得一个随机整数,但最初的问题是如何生成随机整数(复数):
如何在Python中生成介于0和9(含)之间的随机整数?
为了清楚起见,这里我们演示如何获得多个随机整数。
鉴于
>>> import random
lo = 0
hi = 10
size = 5
Code
多个随机整数
# A
>>> [lo + int(random.random() * (hi - lo)) for _ in range(size)]
[5, 6, 1, 3, 0]
# B
>>> [random.randint(lo, hi) for _ in range(size)]
[9, 7, 0, 7, 3]
# C
>>> [random.randrange(lo, hi) for _ in range(size)]
[8, 3, 6, 8, 7]
# D
>>> lst = list(range(lo, hi))
>>> random.shuffle(lst)
>>> [lst[i] for i in range(size)]
[6, 8, 2, 5, 1]
# E
>>> [random.choice(range(lo, hi)) for _ in range(size)]
[2, 1, 6, 9, 5]
随机整数样本
# F
>>> random.choices(range(lo, hi), k=size)
[3, 2, 0, 8, 2]
# G
>>> random.sample(range(lo, hi), k=size)
[4, 5, 1, 2, 3]
细节
一些帖子演示了如何本机生成多个随机整数。1以下是一些解决隐含问题的选项:
A: random.random返回范围为[0.0,1.0)的随机浮点值B: random.randit返回一个随机整数N,使得a<=N<=BC: random.randrange别名到randint(a,b+1)D: random.shuffle将序列打乱E: random.choice从非空序列中返回一个随机元素F: random.choices从总体中返回k个选择(带替换,Python 3.6+)G: random.sample从总体中返回k个唯一选择(无替换):2
另请参阅R.Hettinger使用随机模块中的示例讨论分块和别名。
以下是标准库和Numpy中一些随机函数的比较:
| | random | numpy.random |
|-|-----------------------|----------------------------------|
|A| random() | random() |
|B| randint(low, high) | randint(low, high) |
|C| randrange(low, high) | randint(low, high) |
|D| shuffle(seq) | shuffle(seq) |
|E| choice(seq) | choice(seq) |
|F| choices(seq, k) | choice(seq, size) |
|G| sample(seq, k) | choice(seq, size, replace=False) |
您还可以将Numpy中的许多分布中的一个快速转换为随机整数的样本。3
示例
>>> np.random.normal(loc=5, scale=10, size=size).astype(int)
array([17, 10, 3, 1, 16])
>>> np.random.poisson(lam=1, size=size).astype(int)
array([1, 3, 0, 2, 0])
>>> np.random.lognormal(mean=0.0, sigma=1.0, size=size).astype(int)
array([1, 3, 1, 5, 1])
1Namely@John Lawrence Aspden、@S T Mohammed、@SiddTheKid、@user14372、@zangw等。2@prashanth提到这个模块显示一个整数。3由@Siddharth Satpathy演示
试试看:
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)