Ling
Ling

Reputation: 911

How to generate specific random numbers in Python?

I need help with generating a list of specific random numbers using Python.

I know how to generate a list of random number like this

import random
number = random.sample(xrange(1,10), 3)

which will generate 3 random numbers between 1 to 10. (Example)

[7, 6, 1]

What I want to do achieve is generating a list of random numbers like this with duplicate value(Example)

[10000, 30000, 20000, 60000, 100, 3000, 3000, 100, ...]

But using above script like this

import random
number = random.sample(xrange(10000,100000), 4)

yields following result (Example)

[12489, 43177, 51867, 68831]

Is it possible to do what I want to achieve here? Thank your answer.

Upvotes: 0

Views: 3330

Answers (3)

Commoner
Commoner

Reputation: 1768

Try this:

import numpy as np
array1 = np.random.randint(8, size=10)
array2 = np.random.randint(6, size=10)
array3 = (np.power(10, array2)) * array1

Arrays 'array1', 'array2' and 'array3' are (examples):

array1 = [2 3 6 7 5 1 1 5 5 7]
array2 = [2 4 1 3 4 5 2 2 4 2]
array3 = [200 30000 60 7000 50000 100000 100 500 50000 700]

array3 is what you want.

Upvotes: 0

Paul Panzer
Paul Panzer

Reputation: 53089

Something that looks like your example

import random
n1 = random.sample(xrange(1,10), 4)
n2 = random.sample(xrange(2,6), 4)
numbers = [n1i * 10**n2i for n1i, n2i in zip(n1, n2)]

Sample output:

[800000, 7000, 200, 30000]

If you want repeats:

random.choices(numbers, k=6)

Sample output:

[800000, 7000, 800000, 800000, 7000, 200]

Upvotes: 2

James
James

Reputation: 36746

Are you looking for random numbers rounded to the thousands?

import random
numbers = [1000*x for x in random.sample(xrange(1,100), 4)]

Upvotes: 2

Related Questions