如何生成n个k位的随机整数

时间:2016-08-23 22:13:57

标签: python

有没有办法创建k个数字的n个随机整数。

例如..包含[0, 2, 3]

的2000个随机整数

我的诀窍是使用随机数的生成器,然后根据范围分配值?

但是想知道在python中有没有更好的方法呢?

编辑: 实例:[0,0,0,2,2,3,0,0,2,2,...... 2000元素],包括0.2和3 我的方法

    def assign(x):
        if x< 0.3: return 0
        elif x<0.6: return 2
        else: return 3

    x = np.random.rand(num)

    x = map(lamdba x:assign(x),x)

5 个答案:

答案 0 :(得分:3)

从它的声音来看,您似乎只想使用列表n中找到的值生成长度为k的序列。

Python的random.choice函数与列表理解相结合是完美的。

以下函数将生成一个长度为n的列表,其中每个元素都是从k中选择的随机元素。

from random import choice

def random_choices(n, k):
    return [choice(k) for _ in xrange(n)]

这与简单列表理解相同。

from random import choice
foo = [choice(k) for _ in xrange(n)]

*感谢Mr.goosberry指出xrange应该在python 3.x.x中替换为range

答案 1 :(得分:1)

现在,在您编辑之后,很清楚您想要什么。您希望对容器中的某些元素进行离散采样。

准备你的课程并做到这一点:

import numpy as np
classes = [0, 2, 3]
samples = np.random.choice(classes, 2000)

如果你想要一些特定的概率:

import numpy as np
classes = [0, 2, 3]
samples = np.random.choice(classes, 2000, p=[0.3, 0.3, 0.4])

请参阅docs

实施应该比您的方法快得多,有时称为轮盘式采样或线性搜索采样。 wiki提到了一些可能的算法。

答案 2 :(得分:1)

您可以通过list comprehension来实现。为了显示我使用20的结果。根据您的要求将其更改为2000

>>> import random
>>> x = 20
>>> [random.choice([0, 2, 3]) for i in range(20)]
[2, 2, 3, 2, 0, 2, 3, 2, 3, 3, 3, 0, 3, 2, 3, 2, 3, 2, 3, 2]

答案 3 :(得分:1)

你愿意使用numpy,所以我建议你使用np.random.choice,即:

import numpy as np

N = 2000
print[np.random.choice([0, 2, 3], p=[1/3.0, 1/3.0, 1/3.0]) for x in range(N)]

答案 4 :(得分:0)

import numpy as np
N = 10
# Generate three vectors of n size
zeros = np.zeros((N,), dtype = np.int) 
twos = np.zeros((N,), dtype = np.int) + 2
threes = np.zeros((N,), dtype = np.int) + 3
# Permutate all together
df = []
df = np.append(df, [zeros, twos, threes])
df_shuffled = np.random.shuffle(df)
print(df)
相关问题