📜  Python中的 random.setstate()

📅  最后修改于: 2022-05-13 01:55:22.678000             🧑  作者: Mango

Python中的 random.setstate()

Random模块用于在Python中生成随机数。实际上不是随机的,而是用于生成伪随机数。这意味着可以确定这些随机生成的数字。

随机.setstate()

random模块的setstate() () 方法与getstate()方法结合使用。使用getstate()方法捕获随机数生成器的状态后,使用 setstate( setstate()方法将随机数生成器的状态恢复到指定状态。

setstate()方法需要一个状态对象作为参数,该参数可以通过调用getstate()方法获得。

示例 1:

# import the random module
import random
  
# capture the current state
# using the getstate() method
state = random.getstate()
  
# print a random number of the
# captured state
num = random.random()
print("A random number of the captured state: "+ str(num))
  
# print another random number
num = random.random()
print("Another random number: "+ str(num))
  
# restore the captured state
# using the setstate() method
# pass the captured state as the parameter
random.setstate(state)
  
# now printing the same random number
# as in the captured state
num = random.random()
print("The random number of the previously captured state: "+ str(num))

输出:

示例 2:

# import the random module
import random
  
  
list1 = [1, 2, 3, 4, 5]  
  
# capture the current state
# using the getstate() method
state = random.getstate()
  
# Prints list of random items of given length 
print(random.sample(list1, 3)) 
  
# restore the captured state
# using the setstate() method
# pass the captured state as the parameter
random.setstate(state)
  
# now printing the same list of random
# items
print(random.sample(list1, 3)) 

输出:

[5, 2, 4]
[5, 2, 4]