如何在Python中生成随机数据?详细代码示例

2021年11月16日20:33:45 发表评论 991 次浏览

使用 Python 中的 random、os 和 secrets 内置模块生成随机整数、浮点数、字符串和字节,包括一些完整的Python中生成随机数据示例。

随机性是随处可见,从加密机器学习。没有随机数的产生,很多事情是不可能完成的,在密码学的情况下,一切都是可以预测的,很容易被破解。

如何在Python中生成随机数据?随机数生成器(RNG)是从随机性的真实源,其可以是可靠的用于加密使用产生随机数的序列的系统(软件或硬件组件)。但是,有伪随机数生成器(PRNG),它生成看似随机但实际上是确定性的随机数,这意味着如果知道 PRNG 的状态(或种子),我们就可以重现它。

Python如何生成随机数据?在本教程中,你将学习如何使用内置的random模块在 Python 中生成随机数、字符串和字节,该模块实现了伪随机数生成器(这意味着,你不应将其用于加密用途,例如密钥或密码生成)。

我们还将探索用于生成适用于密码、加密密钥、帐户身份验证和相关机密的加密安全随机数的secrets模块。

相关: 如何在 Python 中使用 Pickle 进行对象序列化。

生成随机整数

Python中生成随机数据示例:要生成随机整数,我们可以使用random.randint()或random.randrange()函数,让我们看看区别:

import random
import os
import string

# generate random integer between a and b (including a and b)
randint = random.randint(1, 500)
print("randint:", randint)

# generate random integer from range
randrange = random.randrange(0, 500, 5)
print("randrange:", randrange)

输出:

randint: 87
randrange: 80

random.randint()函数返回之间的随机整数一个和b(在此情况下,1和500),其包括一个和b,换句话说:一个<= X <= B。

而random.randrange()从该范围(start=0 , stop=500 , step=5 )中选择一个随机项,可以是0、5、10、15等等,直到500。

随机选择元素

如何在Python中生成随机数据?假设我们有一个很大的元素列表,我们想随机选择一个项目,random.choice()来救援:

# get a random element from this list
choice = random.choice(["hello", "hi", "welcome", "bye", "see you"])
print("choice:", choice)

这将从该列表中随机选择一个元素,这是输出:

choice: hi

如果你希望一次选择多个元素,你可以使用random.choices()函数代替:

# get 5 random elements from 0 to 1000
choices = random.choices(range(1000), k=5)
print("choices:", choices)

这将从该范围中选择 5 个元素:

choices: [889, 832, 537, 110, 130]

Python如何生成随机数据?生成浮点数

你还可以生成浮点数:

# generate a random floating point number from 0.0 <= x <= 1.0
randfloat = random.random()
print("randfloat between 0.0 and 1.0:", randfloat)

输出:

randfloat between 0.0 and 1.0: 0.49979177801639296

如果要在 2 个数字之间生成浮点数,可以使用random.uniform()函数:

# generate a random floating point number such that a <= x <= b
randfloat = random.uniform(5, 10)
print("randfloat between 5.0 and 10.0:", randfloat)

这将生成5到10之间的任何浮点数:

randfloat between 5.0 and 10.0: 5.258643397238765

Python中生成随机数据示例:混洗序列

为了在 Python 中随机混洗任何可迭代对象,你可以使用random.shuffle()函数,这是一个示例:

l = list(range(10))
print("Before shuffle:", l)
random.shuffle(l)
print("After shuffle:", l)

输出:

Before shuffle: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
After shuffle: [7, 8, 4, 5, 6, 9, 2, 1, 0, 3]

生成字符串

在random模块中没有直接生成随机字符串的方法。但是,我们可以使用random.sample( ) 或random.choices()函数从字符列表中随机选择字符:

# generate a random string
randstring = ''.join(random.sample(string.ascii_letters, 16))
print("Random string with 16 characters:", randstring)

这将从string.ascii_letters生成16 个字符(如我们指定的那样),其中包括所有ASCII 字符

Random string with 16 characters: MjIRHEGnxCSNeAiv

你还可以使用string.ascii_letters + string.digits添加数字,或者你可以使用string.ascii_lowercase仅使用小写字符。

如何在Python中生成随机数据?密码安全生成

正如我们之前提到的,随机 模块对于密码生成或任何加密用途都非常不安全。事实上,你甚至可以使用random.seed()函数来设置随机性的种子,它会在你每次运行程序时生成相同的数字序列,这对于机器学习或其他目的很有用。

Python中生成随机数据示例 - 但是,对于加密用途,你应该使用secrets模块代替,以下代码行安全地随机生成不同类型的数据:

# crypto-safe byte generation
randbytes_crypto = os.urandom(16)
print("Random bytes for crypto use using os:", randbytes_crypto)

# or use this
randbytes_crypto = secrets.token_bytes(16)
print("Random bytes for crypto use using secrets:", randbytes_crypto)

# crypto-secure string generation
randstring_crypto = secrets.token_urlsafe(16)
print("Random strings for crypto use:", randstring_crypto)

# crypto-secure bits generation
randbits_crypto = secrets.randbits(16)
print("Random 16-bits for crypto use:", randbits_crypto)

这是输出:

Random bytes for crypto use using os: b'\xf4\xa1\xed\xb3\xef)\xfe\xd2\xe6\x86\xdb&=\xff\xf5\x9c'
Random bytes for crypto use using secrets: b'\x99^\x96\x90\xe93[\x1d\x86C\xe8\xcf\x1f\xa3\x06\x86'
Random strings for crypto use: RJDD-8iCEsAuDC1-N9EbQA
Random 16-bits for crypto use: 2371

还学习: 如何使用 hashlib 在 Python 中使用哈希算法。

结论

如何在Python中生成随机数据?在以上实践中,你应该使用random模块进行统计建模、模拟、机器学习和其他目的(你也可以使用numpy的 random 模块来生成随机数组),生成可重现的随机数据,这比密码安全要快得多发电机。

Python如何生成随机数据?你应该只将secrets 模块用于数据安全至关重要的加密应用程序。

有关更多信息,你可以查看 Python 官方文档,了解本教程中使用的不同模块:

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: