Python random.setstate()

Python random.setstate()

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

random.setstate()

随机模块的setstate()方法与getstate()方法结合使用。在使用getstate()方法获取随机数发生器的状态后,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))

输出:

A random number of the captured state: 0.8059083574308233
Another random number: 0.46568313950438245
The random number of the previously captured state: 0.8059083574308233

例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]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程