当前位置:首页>python>python的random库中更高级的函数用法

python的random库中更高级的函数用法

  • 2026-09-02 18:52:09
python的random库中更高级的函数用法
关注+星标,每天学习Python新技能

来源:网络

random库相信大家都用过,我们都用它来生成随机数,本篇主要回顾下这个库中高级用法,让我们开始,本篇所有代码假设你已经导入了random库。

random.seed()

此功能虽然鲜为人知,但可能仍然是此列表中最常用的功能, 此函数用于设置随机数生成器的状态, Python 的随机库实际上是伪随机的, 这意味着可以预测返回值,如果我们对两个相同的随机过程使用相同的种子,我们将得到相同的结果。这是一个例子:

print("first run:")random.seed(0)print(random.random())print(random.random())print("second run:")random.seed(0)print(random.random())print(random.random())

输出:

firstrun:0.84442185152504810.7579544029403025secondrun:0.84442185152504810.7579544029403025

正如我们所看到的,如果我们将种子设置为相同的值,我们会得到相同的结果, 此函数与其他伪随机函数协同作用:

x=list(range(10000))print("first run:")random.seed(0)print(random.randrange(2000,3000))print(random.choice(x))print("second run:")random.seed(0)print(random.randrange(2000, 3000))print(random.choice(x))

输出:

firstrun:28646311secondrun:28646311

random.getstate()/random.setstate()

这两个函数一起使用,类似于前面的 random.seed() 函数,但是,它们允许你存储状态并在以后重用它, 这是一个例子:

state=random.getstate()print(random.random())print(random.random())print("after resetting the state:")random.setstate(state)print(random.random())print(random.random())

输出:

0.36788996299556040.09259531746179073afterresettingthestate:0.36788996299556040.09259531746179073

random.uniform()

此函数与 random.randint() 函数非常相似,但它返回两个参数之间的浮点值:min 和 max。

foriinrange(10):print(random.uniform(15, 47))

输出:

31.47649542678213746.7346309517241921.31453020237320618.14559672221898636.67951985772937526.21838172604052319.09960060434375333.6360628394591342.0969498438171921.800395379104877

random.sample()

最后,此函数从列表中获取给定数量的样本:

random.sample(population, k)

population 是要抽样的列表,k 是需要的样本数。此函数返回一个列表。

x=list(range(10))print(random.sample(x, k=10))

输出:

[2, 8, 0, 4, 3, 6, 5, 9, 7, 1]

另一种可能性是为每个值添加权重以给出偏差:

x=list(range(10))print("without weights:")print(random.sample(x, k=10))print("with weights")print(random.sample(x, counts=[1,10,1,1,1,5,1,1,1,1], k=10))

输出:

withoutweights:[3, 8, 5, 4, 2, 7, 1, 6, 9, 0]withweights[3, 1, 8, 4, 6, 1, 5, 1, 1, 1]

非常感谢阅读,本篇完。

参考:https://www.raaicode.com/more-advanced-functions-in-pythons-random-library/

长按或扫描下方二维码,免费获取 Python公开课和大佬打包整理的几百G的学习资料,内容包含但不限于Python电子书、教程、项目接单、源码等等

推荐阅读

Python数据库大揭秘:7款不为人知的宝藏工具

9个提升Python代码生产质量的第三方库

Python 常见配置文件写法全解,这篇超全攻略必看!

总结:Python 的 NumPy 技术库的完整介绍和知识总结

点击 阅读原文 了解更多

最新文章

随机文章