Python - generate same random numbers

2019-06-14 02:24发布

问题:

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]