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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。