Python random.randint多久生成一次相同的数字?
我想在两端生成0-9(包括0-9)之间的随机整数,但我想确保它通常不会连续生成相同的数字。我计划使用随机模块中的randint函数。但我不确定它是否方便。random.randint多久生成一次相同的数字?如果说random,你可以假设它们是一致随机的,除非另有说明,即所有可能的结果都有相同的概率 为了在不生成连续数字的情况下生成数字,最简单的方法是制作自己的生成器:Python random.randint多久生成一次相同的数字?,python,random,integer,Python,Random,Integer,我想在两端生成0-9(包括0-9)之间的随机整数,但我想确保它通常不会连续生成相同的数字。我计划使用随机模块中的randint函数。但我不确定它是否方便。random.randint多久生成一次相同的数字?如果说random,你可以假设它们是一致随机的,除非另有说明,即所有可能的结果都有相同的概率 为了在不生成连续数字的情况下生成数字,最简单的方法是制作自己的生成器: def random_non_repeating(min, max=None): if not max:
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
如果说随机,你可以假设它们是一致随机的,除非另有说明,即所有可能的结果都有相同的概率
为了在不生成连续数字的情况下生成数字,最简单的方法是制作自己的生成器:
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
为什么不包装兰丁
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()
...
为什么不包装兰丁
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()
...
为了避免重复,您可以使用这样一个简单的包装器,有关其工作原理的说明,请参见:
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))
为了避免重复,您可以使用这样一个简单的包装器,有关其工作原理的说明,请参见:
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
无需while循环即可轻松完成
next_random_number = (previous_random_number + random.randint(1,9)) % 10
假设它足够随机,两次得到相同数字的概率是10%。假设它足够随机,两次得到相同数字的概率是10%。哇,我完全错过了问题中避免重复、连续生成的部分,+1。也就是说,我确实觉得生成器是一个更优雅的解决方案。哇,我完全忽略了问题中避免重复、连续生成的部分,+1。也就是说,我确实觉得生成器在这里是一个更优雅的解决方案。我觉得使用生成器获取随机数并不自然。你为什么要通过islice 100?如果您想让它结束,只需传递None。@Lattyware使用生成器获取单个随机数的语法很麻烦。@Lattyware:到什么目的?罗伯特:问题是生成一个不重复的随机数序列。我觉得用生成器来获取随机数是不自然的。你为什么要通过islice 100?如果您想让它结束,只需传递None。@Lattyware使用生成器获取单个随机数的语法很麻烦。@Lattyware:到什么目的?罗伯特:问题是关于生成一个不重复的随机数序列。请解释你的答案。嗨,你可以用列表生成随机数,而不是重复的。请解释你的答案。嗨,你可以使用列表来生成随机数,而不是重复,这是一种非常简洁高效的方法。