Fraz - 1 month ago 5x

Python Question

Is there a way to create n random integers of k digits.

For example.. 2000 random integers comprising of

`[0, 2, 3]`

My trick was to use a random number of generator and then assign values based on the the ranges?

But was wondering if there is a better way to do this in python?

Edit:

Example: [0,0,0, 2, 2,3,0,0,2,2,..... 2000 elements] comprising of 0,2 and 3

my approach

`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)

Answer

From the sounds of it, it looks like you want to generate a sequence of length `n`

using only the values found within the list `k`

.

Python's `random.choice`

function combined with list comprehension is perfect for this.

The following function will generate a list of length n with each element being a random element chosen from `k`

.

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

Here is the same thing as simple list comprehension.

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

*Thanks to Mr.goosberry for pointing out that `xrange`

should be replaced with `range`

in python 3.x.x.

Source (Stackoverflow)

Comments