簡體   English   中英

random.randint多久生成一次相同的數字?

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

Python文檔隨機的地方除非另有說明(即所有可能的結果具有相等的概率),否則您可以假設它們的意思是統一隨機的。

為了生成數字而不生成連續的數字,最簡單的選擇是制作自己的生成器:

def random_non_repeating(min, max=None):
    if not max:
        min, max = 0, min
    old = None
    while True:
        current = random.randint(min, max)
        if not old == current:
            old = current
            yield current

為了避免重復,您可以使用像這樣的簡單包裝器(有關其工作原理的說明,請參見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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM