Python - generate same random numbers

怎甘沉沦 提交于 2020-01-03 05:18:52

问题


def main():
    x = [randint(1,100) for i in range(1,100)]
    return x

This returns 100 random numbers btw 1 and 100. Each time I call the function, it returns a different sequence of numbers. What I want to, is to get the same sequence of numbers each time. maybe saving the results into sth?


回答1:


You can provide some fixed seed.

import random

def main():
    random.seed(9001)
    x = [random.randint(1,100) for i in range(1,100)]
    return x

For more information on seed: random.seed(): What does it do?




回答2:


Here's a basic example patterned after your code

import random
s = random.getstate()

print([random.randint(1,100) for i in range(10)])

random.setstate(s)
print([random.randint(1,100) for i in range(10)])

In both invocations, you get identical output. The key is, at any point you can retrieve and later reassign the current state of the rng.




回答3:


In [19]: for i in range(10):
    ...:     random.seed(10)
    ...:     print [random.randint(1, 100) for j in range(5)]
    ...:
    ...:
[58, 43, 58, 21, 82]
[58, 43, 58, 21, 82]
[58, 43, 58, 21, 82]
[58, 43, 58, 21, 82]
[58, 43, 58, 21, 82]
[58, 43, 58, 21, 82]
[58, 43, 58, 21, 82]
[58, 43, 58, 21, 82]
[58, 43, 58, 21, 82]
[58, 43, 58, 21, 82]

The random.seed function has to be called just before a fresh call to random.

In [20]: random.seed(10)

In [21]: for i in range(10):
    ...:     print [random.randint(1,10) for j in range(10)]
    ...:
[5, 6, 3, 9, 9, 7, 2, 6, 4, 3]
[10, 10, 1, 9, 7, 4, 3, 7, 5, 7]
[7, 2, 8, 10, 10, 7, 1, 1, 2, 10]
[4, 4, 9, 4, 6, 5, 1, 6, 9, 2]
[3, 5, 1, 5, 9, 7, 6, 9, 2, 6]
[4, 7, 2, 8, 1, 2, 9, 10, 5, 5]
[3, 3, 7, 2, 2, 5, 2, 7, 9, 8]
[5, 4, 5, 1, 8, 4, 4, 1, 5, 6]
[4, 9, 7, 3, 6, 10, 6, 7, 1, 5]
[5, 5, 5, 6, 6, 5, 2, 5, 10, 5]


来源:https://stackoverflow.com/questions/42689301/python-generate-same-random-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!