[英]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.