Generate random integers between 0 and 9

2019-01-01 11:53发布

问题:

How can I generate random integers between 0 and 9 (inclusive) in Python?

For example, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

回答1:

Try:

from random import randint
print(randint(0, 9))

More info: https://docs.python.org/3/library/random.html#random.randint



回答2:

import random
print(random.randint(0,9))

random.randint(a, b)

Return a random integer N such that a <= N <= b.

Docs: https://docs.python.org/3.1/library/random.html#random.randint



回答3:

Try this:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)


回答4:

from random import randint

x = [randint(0, 9) for p in range(0, 10)]

This generates 10 pseudorandom integers in range 0 to 9 inclusive.



回答5:

The secrets module is new in Python 3.6. This is better than the random module for cryptography or security uses.

To randomly print an integer in the inclusive range 0-9:

from secrets import randbelow
print(randbelow(10))

For details, see PEP 506.



回答6:

Try this through random.shuffle

>>> import random
>>> nums = [x for x in range(10)]
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]


回答7:

Choose the size of the array (in this example, I have chosen the size to be 20). And then, use the following:

import numpy as np   
np.random.randint(10, size=(1, 20))

You can expect to see an output of the following form (different random integers will be returned each time you run it; hence you can expect the integers in the output array to differ from the example given below).

array([[1, 6, 1, 2, 8, 6, 3, 3, 2, 5, 6, 5, 0, 9, 5, 6, 4, 5, 9, 3]])


回答8:

In case of continuous numbers randint or randrange are probably the best choices but if you have several distinct values in a sequence (i.e. a list) you could also use choice:

>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5

choice also works for one item from a not-continuous sample:

>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7

If you need it \"cryptographically strong\" there\'s also a secrets.choice in python 3.6 and newer:

>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2


回答9:

if you want to use numpy then use the following:

import numpy as np
print(np.random.randint(0,10))


回答10:

The original question implies generating multiple random integers.

How can I generate integers between 0 and 9 (inclusive) in Python?

Many responses however only show how to get one random number, e.g. random.randint and random.choice.

Multiple Random Integers

For clarity, you can still generate multiple random numbers using those techniques by simply iterating N times:

import random


N = 5

[random.randint(0, 9) for _ in range(N)]
# [9, 7, 0, 7, 3]

[random.choice(range(10)) for _ in range(N)]
# [8, 3, 6, 8, 7]

Sample of Random Integers

Some posts demonstrate how to natively generate multiple random integers.1 Here are some options that address the implied question:

random.sample returns k unique selections from a population (without replacement):2

random.sample(range(10), k=N)
# [4, 5, 1, 2, 3]

In Python 3.6, random.choices returns k selections from a population (with replacement):

random.choices(range(10), k=N)
# [3, 2, 0, 8, 2]

See also this related post using numpy.random.choice.

1Namely @John Lawrence Aspden, @S T Mohammed, @SiddTheKid, @user14372, @zangw, et al.

2@prashanth mentions this module showing one integer.



回答11:

>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1

To get a list of ten samples:

>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]


回答12:

random.sample is another that can be used

import random
n = 1 # specify the no. of numbers
num = random.sample(range(10),  n)
num[0] # is the required number


回答13:

Generating random integers between 0 and 9.

import numpy
X = numpy.random.randint(0, 10, size=10)
print(X)

Output:

[4 8 0 4 9 6 9 9 0 7]


回答14:

Best way is to use import Random function

import random
print(random.sample(range(10), 10))

or without any library import:

n={} 
for i in range(10):
    n[i]=i

for p in range(10):
    print(n.popitem()[1])

here the popitems removes and returns an arbitrary value from the dictionary n.



回答15:

I used variable to control the range

from random import randint 
numberStartRange = 1
numberEndRange = 9
randomNumber = randint(numberStartRange, numberEndRange)
print(randomNumber)

I used the print function to see the results. You can comment is out if you do not need this.



回答16:

For the example that you have given (integers starting from 0 and going until 9), the cleanest solution is as follows:

from random import randrange

randrange(10)


回答17:

This is more of a mathematical approach but it works 100% of the time:

Let\'s say you want to use random.random() function to generate a number between a and b. To achieve this, just do the following:

num = (b-a)*random.random() + a;

Of course, you can generate more numbers.



回答18:

You can try this:

import numpy as np
print ( np.random.uniform(low=0, high=10, size=(15,)) ).astype(int)

>>> [8 3 6 9 1 0 3 6 3 3 1 2 4 0 4]

Notes:

1.> np.random.uniform generates uniformly distributed numbers over the half-open interval [low, high).

2.> astype(int) casts the numpy array to int data type.

3.> I have chosen size = (15,). This will give you a numpy array of length = 15.

More information on numpy.random.uniform

More information on numpy.ndarray.astype



回答19:

From the documentation page for the random module:

Warning: The pseudo-random generators of this module should not be used for security purposes. Use os.urandom() or SystemRandom if you require a cryptographically secure pseudo-random number generator.

random.SystemRandom, which was introduced in Python 2.4, is considered cryptographically secure. It is still available in Python 3.7.1.

>>> import string
>>> string.digits
\'0123456789\'
>>> import random
>>> random.SystemRandom().choice(string.digits)
\'8\'
>>> random.SystemRandom().choice(string.digits)
\'1\'
>>> random.SystemRandom().choice(string.digits)
\'8\'
>>> random.SystemRandom().choice(string.digits)
\'5\'

Instead of string.digits, range could be used per some of the other answers along perhaps with a comprehension. Mix and match according to your needs.



回答20:

Try This,

import numpy as np

X = np.random.randint(0, 99, size=1000) # 1k random integer


回答21:

I had better luck with this for Python 3.6

str_Key = \"\"                                                                                                
str_RandomKey = \"\"                                                                                          
for int_I in range(128):                                                                                    
      str_Key = random.choice(\'0123456789\')
      str_RandomKey = str_RandomKey + str_Key 

Just add characters like \'ABCD\' and \'abcd\' or \'^!~=-><\' to alter the character pool to pull from, change the range to alter the number of characters generated.