如何在Python中生成介于0和9(含)之间的随机整数?

例如,0、1、2、3、4、5、6、7、8、9


当前回答

通过random.shuffle尝试

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

其他回答

从随机模块的文档页面:

警告:此模块的伪随机生成器不应用于安全目的。如果需要,请使用os.urantom()或SystemRandom需要密码安全的伪随机数发生器。

Python 2.4中引入的random.SystemRandom被认为是加密安全的。它在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'

除了字符串数字,还可以对其他一些答案使用范围,也许还可以理解。根据您的需要进行混合和搭配。

尝试random.randrange:

from random import randrange
print(randrange(10))

OpenTURNS不仅可以模拟随机整数,还可以使用UserDefined定义的类定义关联的分布。

以下模拟了分布的12个结果。

import openturns as ot
points = [[i] for i in range(10)]
distribution = ot.UserDefined(points) # By default, with equal weights.
for i in range(12):
    x = distribution.getRealization()
    print(i,x)

这将打印:

0 [8]
1 [7]
2 [4]
3 [7]
4 [3]
5 [3]
6 [2]
7 [9]
8 [0]
9 [5]
10 [9]
11 [6]

括号在那里,因为x是一维中的一个点。在对getSample的一次调用中生成12个结果会更容易:

sample = distribution.getSample(12)

将产生:

>>> print(sample)
     [ v0 ]
 0 : [ 3  ]
 1 : [ 9  ]
 2 : [ 6  ]
 3 : [ 3  ]
 4 : [ 2  ]
 5 : [ 6  ]
 6 : [ 9  ]
 7 : [ 5  ]
 8 : [ 9  ]
 9 : [ 5  ]
10 : [ 3  ]
11 : [ 2  ]

有关此主题的更多详细信息,请参见:http://openturns.github.io/openturns/master/user_manual/_generated/openturns.UserDefined.html

通过random.shuffle尝试

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

要获得十个样本的列表:

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