📜  Python中的 random.getstate()

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

Python中的 random.getstate()

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

随机.getstate()

random 模块的 getstate() 方法返回一个具有随机数生成器当前内部状态的对象。可以将此对象传递给 setstate() 方法以恢复状态。此方法中没有传递任何参数。
示例 1:

Python3
import random
 
 
# remember this state
state = random.getstate()
 
# print 10 random numbers
print(random.sample(range(20), k = 10))
 
# restore state
random.setstate(state)
 
# print same first 5 random numbers
# as above
print(random.sample(range(20), k = 5))


Python3
import random
   
 
list1 = [1, 2, 3, 4, 5, 6] 
     
# Get the state
state = random.getstate()
 
# prints a random value from the list
print(random.choice(list1))
   
# Set the state
random.setstate(state)
 
# prints the same random value
# from the list
print(random.choice(list1))


输出:

[16, 1, 0, 11, 19, 3, 7, 5, 10, 13]
[16, 1, 0, 11, 19]

示例 2:

Python3

import random
   
 
list1 = [1, 2, 3, 4, 5, 6] 
     
# Get the state
state = random.getstate()
 
# prints a random value from the list
print(random.choice(list1))
   
# Set the state
random.setstate(state)
 
# prints the same random value
# from the list
print(random.choice(list1))

输出:

3
3