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:18

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
查看更多
路过你的时光
3楼-- · 2019-01-01 12:19

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楼-- · 2019-01-01 12:20
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

查看更多
人气声优
5楼-- · 2019-01-01 12:20
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.

查看更多
人气声优
6楼-- · 2019-01-01 12:20

if you want to use numpy then use the following:

import numpy as np
print(np.random.randint(0,10))
查看更多
步步皆殇っ
7楼-- · 2019-01-01 12:20

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)
查看更多
登录 后发表回答