Generate random integers between 0 and 9

2019-01-01 11:57发布

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

21条回答
荒废的爱情
2楼-- · 2019-01-01 12:14

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
查看更多
无与为乐者.
3楼-- · 2019-01-01 12:14

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.

查看更多
路过你的时光
4楼-- · 2019-01-01 12:15

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]])
查看更多
忆尘夕之涩
5楼-- · 2019-01-01 12: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.

查看更多
妖精总统
6楼-- · 2019-01-01 12:16

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楼-- · 2019-01-01 12:17
>>> 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]
查看更多
登录 后发表回答