Generating List of N Random Numbers Between a Range of Numbers

匆匆过客 提交于 2020-01-11 13:05:45

问题


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

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