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]

版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com

目录[+]

取消
微信二维码
微信二维码
支付宝二维码