The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state.
因此,您只需创建自己的random.Random实例,并使用它自己的种子,这根本不会影响全局函数:
>>> import random
>>> x = [1, 2, 3, 4, 5, 6]
>>> random.Random(4).shuffle(x)
>>> x
[4, 6, 5, 1, 3, 2]
>>> x = [1, 2, 3, 4, 5, 6]
>>> random.Random(4).shuffle(x)
>>> x
[4, 6, 5, 1, 3, 2]
def rand_tracker():
rand_tracker.count += 1
return random()
rand_tracker.count = 0
shuffle(v, random = rand_tracker)
print 'Random function was called %d times for length %d list.' % (rand_tracker.count, len(v))
这表明:
Random function was called 999 times for length 1000 list.
您可以设置随机生成器的
seed
(它接受parameter
),这将决定您的洗牌方法结果应该是
为了“重新处理”剩下的代码,您可以通过运行
在你的“确定性”代码之后
正如the documentation所解释的:
因此,您只需创建自己的
random.Random
实例,并使用它自己的种子,这根本不会影响全局函数:(您也可以在
Random
实例周围保留并重新创建seed
实例,而不是一遍又一遍地创建新的实例;没有太大的区别。)使用
random
的固定值洗牌不起作用!示例:给出输出:
其他种子也一样-不是很随机的(不管怎么说第一眼。。。很难证明)。这是因为
random
不是种子-它被多次重用。演示:这表明:
你应该做的是@abarnert的建议:
在这种情况下,固定值是完全正确的。
TLDR:使用@abarnert的答案,不要为
random
使用固定值函数!相关问题 更多 >
编程相关推荐