如何在python中设置种子后获得真正的随机数

如何在python中设置种子后获得真正的随机数,python,python-3.x,Python,Python 3.x,对于部分代码,我需要在每次运行代码时获得相同的“随机”数字,并使用random.seed(0)确保每次返回相同的数字。但是,在代码的另一部分,我希望每次运行代码时都有不同的数字。但是,一旦设置了种子,每次调用任意随机函数时,它们返回的数字总是相同的。如何将预先确定的随机数与随机数组合起来?您可以使用getstate和setstate,这两种方法大致如下: import random state = random.getstate() # saving the current state of

对于部分代码,我需要在每次运行代码时获得相同的“随机”数字,并使用
random.seed(0)
确保每次返回相同的数字。但是,在代码的另一部分,我希望每次运行代码时都有不同的数字。但是,一旦设置了种子,每次调用任意随机函数时,它们返回的数字总是相同的。如何将预先确定的随机数与随机数组合起来?

您可以使用
getstate
setstate
,这两种方法大致如下:

import random

state = random.getstate()  # saving the current state of the generator

random.seed(0)
random.randint(1, 10)

# some more fiddling with random
# ...

random.setstate(state)  # restore the original state

文档中的信息:

使用两个不同的PRNG对象(有时称为流)。一个恒定的种子;一个是时间或外部熵的种子,取决于用例。提示:
r=random.random()
。备注:与不同用途之间的获取/设置内部状态相比,这更简单,性能更高。感谢Sascha-如果这是一个实际的“答案”,我肯定会将其标记为最佳答案!