page contents

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

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

attachments-2026-04-pntZzO3i69e2e3eb45dcb.png

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())

输出:

first run:
0.8444218515250481
0.7579544029403025
second run:
0.8444218515250481
0.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(20003000))
print(random.choice(x))

输出:

first run:
2864
6311
second run:
2864
6311

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.3678899629955604
0.09259531746179073
after resetting the state:
0.3678899629955604
0.09259531746179073


random.uniform()

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

for i in range(10):
   print(random.uniform(1547))

输出:

31.476495426782137
46.73463095172419
21.314530202373206
18.145596722218986
36.679519857729375
26.218381726040523
19.099600604343753
33.63606283945913
42.09694984381719
21.800395379104877

random.sample()

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

random.sample(populationk)

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

x = list(range(10))
print(random.sample(xk=10))

输出:

[2804365971]

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

x = list(range(10))

print("without weights:")
print(random.sample(xk=10))

print("with weights")
print(random.sample(xcounts=[1,10,1,1,1,5,1,1,1,1], k=10))

输出:

without weights:
[3854271690]
with weights
[3184615111]

非常感谢阅读,本篇完。

更多相关技术内容咨询欢迎前往并持续关注好学星城论坛了解详情。

想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。

attachments-2022-05-rLS4AIF8628ee5f3b7e12.jpg

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
Pack
Pack

1963 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 2228 文章
  3. Pack 1963 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章