问题
I'd like to generate a list of n_length consisting of randomly generated numbers within a defined range. What I'd like to know is whether I'm missing something built-in, something that would allow me to do this in the future in a more pythonic and cleaner way. Thanks for any thoughts.
In [59]: from random import randrange
In [60]: x_list = [0]*100
In [61]: rand_list = [randrange(700, 1500) for x in x_list]
Basically, I don't like my x_list
because I think it's kind of arbitrary, and I doubt that I'm the first person ever to encounter this problem, especially where databases store so much info as indices. Is there a better way of solving this? Thanks again.
回答1:
I believe you are looking for
rand_list = [randrange(700, 1500) for _ in xrange(100)]
回答2:
I think this is better if you don't care about the distribution:
>>> random.sample(xrange(700, 1500), 100)
来源:https://stackoverflow.com/questions/17749629/generating-list-of-n-random-numbers-between-a-range-of-numbers