在 Python 中创建随机整数列表 [英] Create random list of integers in Python

查看:24
本文介绍了在 Python 中创建随机整数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个随机整数列表以进行测试.数字的分布并不重要.唯一重要的是时间.我知道生成随机数是一项耗时的任务,但一定有更好的方法.

I'd like to create a random list of integers for testing purposes. The distribution of the numbers is not important. The only thing that is counting is time. I know generating random numbers is a time-consuming task, but there must be a better way.

这是我目前的解决方案:

Here's my current solution:

import random
import timeit

# Random lists from [0-999] interval
print [random.randint(0, 1000) for r in xrange(10)] # v1
print [random.choice([i for i in xrange(1000)]) for r in xrange(10)] # v2

# Measurement:
t1 = timeit.Timer('[random.randint(0, 1000) for r in xrange(10000)]', 'import random') # v1
t2 = timeit.Timer('random.sample(range(1000), 10000)', 'import random') # v2

print t1.timeit(1000)/1000
print t2.timeit(1000)/1000

v2 比 v1 快,但它并没有在这么大的范围内工作.它给出了以下错误:

v2 is faster than v1, but it is not working on such a large scale. It gives the following error:

ValueError:样本大于总体

是否有一种快速、高效的解决方案可以在这种规模下发挥作用?

Is there a fast, efficient solution that works at that scale?

安德鲁的:0.000290962934494

Andrew's: 0.000290962934494

格尼布勒的:0.0058455221653

gnibbler's: 0.0058455221653

KennyTM 的:0.00219276118279

KennyTM's: 0.00219276118279

NumPy 出现、看到并征服了.

NumPy came, saw, and conquered.

推荐答案

你想要什么并不完全清楚,但我会使用 numpy.random.randint:

It is not entirely clear what you want, but I would use numpy.random.randint:

import numpy.random as nprnd
import timeit

t1 = timeit.Timer('[random.randint(0, 1000) for r in xrange(10000)]', 'import random') # v1

### Change v2 so that it picks numbers in (0, 10000) and thus runs...
t2 = timeit.Timer('random.sample(range(10000), 10000)', 'import random') # v2
t3 = timeit.Timer('nprnd.randint(1000, size=10000)', 'import numpy.random as nprnd') # v3

print t1.timeit(1000)/1000
print t2.timeit(1000)/1000
print t3.timeit(1000)/1000

在我的机器上给出:

0.0233682730198
0.00781716918945
0.000147947072983

请注意,randint 非常 与 random.sample 不同(为了让它在您的情况下工作,我不得不将 1,000 更改为 10,000,正如一位评论员指出的那样——如果您真的想要它们从 0 到 1,000,你可以除以 10).

Note that randint is very different from random.sample (in order for it to work in your case I had to change the 1,000 to 10,000 as one of the commentators pointed out -- if you really want them from 0 to 1,000 you could divide by 10).

如果你真的不关心你得到的是什么分布,那么你可能不是很好地理解你的问题,或者是随机数——如果这听起来很粗鲁,请道歉......

And if you really don't care what distribution you are getting then it is possible that you either don't understand your problem very well, or random numbers -- with apologies if that sounds rude...

这篇关于在 Python 中创建随机整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆