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

查看:224
本文介绍了在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?

安德鲁(Andrew):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.

推荐答案

目前尚不清楚您想要什么,但是我会使用

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 完全不同(为了使它能够在您的情况下工作,我必须将1000更改为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天全站免登陆