python维护两个不同的随机实例

2024-09-29 21:33:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试做一些分析,出于“原因”,我希望我的程序中的对象每个都有自己的种子,但没有全局种子。我能完成这样的事情吗?在

a = random.seed(seed1) 
b = random.seed(seed1)

for a in range(5) :
    print a.random(), b.random()

预期输出将是

^{pr2}$

等等。。。 显然,这是一个超级人工的例子——这些单独的种子将被埋藏在对象中,并与特定的事物相对应。但第一步是让这样的东西发挥作用。在

如何让python维护多种子随机数?在


Tags: 对象in程序forrange原因random全局
3条回答

您需要使用random.Random类对象。在

from random import Random

a = Random()
b = Random()

a.seed(0)
b.seed(0)

for _ in range(5):
    print(a.randrange(10), b.randrange(10))

# Output:
# 6 6
# 6 6
# 0 0
# 4 4
# 8 8

documentation明确说明了您的问题:

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 of Random to get generators that don’t share state.

那么,这可能有助于您:

>>> for _ in range(5): 
          rn=random.randint(1,100) 
          print(rn, rn) 

输出为:
38 38

98 98个

8 8

29 29日

67 67

我希望您只是在寻找上述输出中提到的随机数:

这里有一些代码。如果对您有帮助,请检查:

>>> for i in range(5):
        print(random.randint(1,100), random.randint(1,100))

输出如下:

1493年

51 62岁

2012年

9 3个

52 71

相关问题 更多 >

    热门问题