繁体   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