用Python随机数的大数组 [英] Big array with random numbers with python

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

问题描述

我需要生成一个带有随机数(10个数字)的大数组(或列表).我正在尝试像这样:

I need to generate a big array (or list) with random numbers ( 10⁵ numbers) . I was trying like that:

vet = random.sample(range(10),100000)

但是当我尝试运行时:

vet = random.sample(range(10),10000)

示例中的文件"/usr/lib/python2.7/random.py",第320行 引发ValueError(样本大于总体") ValueError:样本大于总体

File "/usr/lib/python2.7/random.py", line 320, in sample raise ValueError("sample larger than population") ValueError: sample larger than population

有解决方案吗?

tkns

推荐答案

您想要的是

[random.random() for _ in xrange(100000)]

来自随机模块文档:

random.sample(population,k)返回k个长度为唯一的元素的列表 从总体序列中选择.用于随机抽样而无需 替换.

random.sample(population, k) Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

因此,在调用random.sample(range(10), 100000)时,您尝试提取长度为10的序列中的100000个唯一元素,这显然是行不通的.

so when calling random.sample(range(10), 100000) you're trying to extract 100000 unique elements in a sequence of length 10 which obviously can't work.

请注意

  • random.random()返回介于[0; 1)
  • random.randrange([start], stop[, step])返回序列range([start], stop[, step])
  • 中的随机元素
  • random.randint(a, b)返回[a;中的整数值; b]
  • 使用random.sample时,必须保持等式len(population) >= k
  • random.random() returns a floating value between [0 ; 1)
  • random.randrange([start], stop[, step]) returns a random element from the sequence range([start], stop[, step])
  • random.randint(a, b) returns an integer value in [a ; b]
  • when using random.sample, the equality len(population) >= k must hold

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

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