当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python random.setstate()用法及代码示例


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

setstate()

setstate()的方法random模块与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]



相关用法


注:本文由纯净天空筛选整理自Yash_R大神的英文原创作品 random.setstate() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。