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

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.

查看更多
弹指情弦暗扣
3楼-- · 2019-01-01 12:28

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]
查看更多
呛了眼睛熬了心
4楼-- · 2019-01-01 12:28

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.

查看更多
登录 后发表回答