阅读本文需要3.5分钟
关于在Python中处理随机性的概述,只使用标准库和CPython本身中内置的功能。
这个random.random()
函数在间隔[0.0,1.0]中返回一个随机浮点。这意味着返回的随机数总是小于右端点(1.0).这也被称为半开放范围:
>>> import random
>>> random.random()
0.11981376476232541
>>> random.random()
0.757859420322092
>>> random.random()
0.7384012347073081
x
和y
这是如何在Python中的两个端点之间生成一个随机整数的方法。random.randint()
功能。这跨越了整个[x,y]间隔,可能包括两个端点:
>>> import random
>>> random.randint(1, 10)
10
>>> random.randint(1, 10)
3
>>> random.randint(1, 10)
7
带着random.randrange()
函数可以排除间隔的右侧,这意味着生成的数字总是位于[x,y]内,并且它总是小于右侧的端点:
>>> import random
>>> random.randrange(1, 10)
5
>>> random.randrange(1, 10)
3
>>> random.randrange(1, 10)
4
x
和y
如果需要生成位于特定[x,y]间隔内的随机浮点数,则可以使用random.uniform
:
>>> import random
>>> random.uniform(1, 10)
7.850184644194309
>>> random.uniform(1, 10)
4.00388600011348
>>> random.uniform(1, 10)
6.888959882650279
要从非空序列(如列表或元组)中选择一个随机元素,可以使用Python的random.choice
:
>>> import random
>>> items = ['one', 'two', 'three', 'four', 'five']
>>> random.choice(items)
'five'
>>> random.choice(items)
'one'
>>> random.choice(items)
'four'
这适用于任何非空序列,如果序列为空,则会出现异常。
可以使用random.shuffle
。这将修改序列对象,并将元素的顺序随机化:
>>> import random
>>> items = ['one', 'two', 'three', 'four', 'five']
>>> random.shuffle(items)
>>> items
['four', 'one', 'five', 'three', 'two']
如果你不想修改原本的,你需要先复制一份,然后在随机。属性创建Python对象的副本。copy
模块。
n
元素列表中的随机样本随机抽样n
序列中的唯一元素,使用random.sample
。它执行随机抽样而不进行替换:
>>> import random
>>> items = ['one', 'two', 'three', 'four', 'five']
>>> random.sample(items, 3)
['one', 'five', 'two']
>>> random.sample(items, 3)
['five', 'four', 'two']
>>> random.sample(items, 3)
['three', 'two', 'five']
如果出于安全目的需要加密安全随机数,使用random.SystemRandom
它使用加密安全的伪随机数生成器。
实例SystemRandom
类的函数提供大多数随机数生成器操作。
下面是一个例子:
>>> import random
>>> rand_gen = random.SystemRandom()
>>> rand_gen.random()
0.6112441459034399
>>> rand_gen.randint(1, 10)
2
>>> rand_gen.randrange(1, 10)
5
>>> rand_gen.uniform(1, 10)
8.42357365980016
>>> rand_gen.choice('abcdefghijklmn')
'j'
>>> items = ['one', 'two', 'three', 'four', 'five']
>>> rand_gen.shuffle(items)
>>> items
['two', 'four', 'three', 'one', 'five']
>>> rand_gen.sample('abcdefghijklmn', 3)
['g', 'e', 'c']
注意SystemRandom
并不保证在所有运行Python的系统上都可用
Python 3.6+-secrets
模块:
如果您正在使用Python 3,并且你的目标是生成加密安全的随机数,那么一定要检查secrets
模块。这个模块可以在Python3.6(及以上)标准库中获得。这使得安全令牌的生成变得很方便。
以下是几个例子:
>>> import secrets
# 生成安全令牌:
>>> secrets.token_bytes(16)
b'\xc4\xf4\xac\x9e\x07\xb2\xdc\x07\x87\xc8 \xdf\x17\x85^{'
>>> secrets.token_hex(16)
'a20f016e133a2517414e0faf3ce4328f'
>>> secrets.token_urlsafe(16)
'eEFup5t7vIsoehe6GZyM8Q'
# 从序列中随机选择一个元素:
>>> secrets.choice('abcdefghij')
'h'
# Securely compare two strings for equality
# (Reduces the risk of timing attacks):
>>> secrets.compare_digest('abcdefghij', '123456789')
False
>>> secrets.compare_digest('123456789', '123456789')
True
您可以了解更多关于secrets
模块在Python 3文档中.