如何将Python的随机数生成器与本地种子一起使用? [英] How to use Python's random number generator with a local seed?
问题描述
Python的随机性似乎是全局的,因此更改它的模块将相互影响.
Python's random seems are global, so modules changing it will effect each other.
虽然当然有很多第三方模块,但是有一种方法可以使用Python的标准库在上下文中使用随机数.
While there are of course many 3rd party modules, is there a way using Python's standard library to have a random number local to a context.
(不使用random.get/setstate
可能会在混合来自不同模块的代码时出现问题).
(without using random.get/setstate
which may be problematic when mixing code from different modules).
类似...
r = random.context(seed=42)
number = r.randint(10, 20)
每个模块都可以使用其自己的随机上下文.
Where each module can use its own random context.
推荐答案
来自文档:
此模块提供的功能实际上是
random.Random
类的隐藏实例的绑定方法.您可以实例化自己的Random
实例,以获取不共享状态的生成器.
The functions supplied by this module are actually bound methods of a hidden instance of the
random.Random
class. You can instantiate your own instances ofRandom
to get generators that don’t share state.
制作您自己的random.Random
实例并使用它.
Make your own random.Random
instance and use that.
rng = random.Random(42)
number = rng.randint(10, 20)
这篇关于如何将Python的随机数生成器与本地种子一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!