用 Python 生成第 n 个随机数

我正在尝试生成用于生成世界一部分的随机数(我正在为游戏进行世界生成)。我可以用类似[random.randint(0, 100) for n in range(1000)]生成 1000 个从 0 到 100 的随机数创建这些,我不知道我需要列表中有多少个数字。我想要的是能够说出类似的东西random.nth_randint(0, 100, 5),它会生成从 0 到 100 的第 5 个随机数。(只要您使用相同的种子,每次都是相同的数字)我该怎么做?如果没有办法做到这一点,我怎么能得到同样的行为呢?


慕的地10843
浏览 161回答 3
3回答

慕姐8265434

如果我理解你的问题,你每次都想要相同的n-th数字。您可以创建一个类来跟踪生成的数字(如果您使用相同的seed)。主要思想是,当您要求 nth-number 时,它将生成所有以前的数字,以便在程序的所有运行中始终相同。import randomclass myRandom():&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self.generated = []&nbsp; &nbsp; &nbsp; &nbsp; #your instance of random.Random()&nbsp; &nbsp; &nbsp; &nbsp; self.rand = random.Random(99)&nbsp; &nbsp; def generate(self, nth):&nbsp; &nbsp; &nbsp; &nbsp; if nth < len(self.generated) + 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self.generated[nth - 1]&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for _ in range(len(self.generated), nth):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.generated.append(self.rand.randint(1,100))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self.generated[nth - 1]r = myRandom()print(r.generate(1))print(r.generate(5))print(r.generate(10))

幕布斯6054654

使用 a defaultdict,您可以拥有一个在第一次访问每个键时生成一个新数字的结构。from collections import defaultdictfrom random import randintrandom_numbers = defaultdict(lambda: randint(0, 100))random_number[5] # 42random_number[5] # 42random_number[0] # 63因此,在访问时会延迟生成数字。由于您正在开发一款游戏,因此您很可能需要random_numbers通过程序中断来进行保存。您可以使用pickle来保存您的数据。import picklerandom_numbers[0] # 24# Save the current statewith open('random', 'wb') as f:&nbsp; &nbsp; pickle.dump(dict(random_numbers), f)# Load the last saved statewith open('random', 'rb') as f:&nbsp; &nbsp; opened_random_numbers = defaultdict(lambda: randint(0, 100), pickle.load(f))opened_random_numbers[0] # 24
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python