[英]How often does random.randint generate the same number?
我想生成介于0到9之间(包括两端)的随机整数,但是我想确保它不会经常连续生成相同的数字。 我计划使用random
模块中的randint
函数。 但是我不确定是否会方便。 random.randint
多久生成一次相同的数字?
为什么不包装randint?
class MyRand(object):
def __init__(self):
self.last = None
def __call__(self):
r = random.randint(0, 9)
while r == self.last:
r = random.randint(0, 9)
self.last = r
return r
randint = MyRand()
x = randint()
y = randint()
...
为了避免重复,您可以使用像这样的简单包装器(有关其工作原理的说明,请参见Fisher-Yates ):
def unique_random(choices):
while True:
r = random.randrange(len(choices) - 1) + 1
choices[0], choices[r] = choices[r], choices[0]
yield choices[0]
使用示例:
from itertools import islice
g = unique_random(range(10))
print list(islice(g, 100))
无需while循环即可轻松完成此操作。
next_random_number = (previous_random_number + random.randint(1,9)) % 10
list =[]
x=0
for i in range(0,10):
while x in list:
x=random.randint(500,1000)
list.append(x)
print sorted(list, key=int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.