我正在做一个程序,我需要生成一个列表随机值。系统要求用户输入要在二维网格上生成的随机值(由字母“T”表示的箱子)。问题是,当用户键入“8”作为他们希望生成的随机“chest”的数量时,有时只有5或6个chest生成到网格(可能是因为随机整数重复到网格上,并且不在网格中的唯一点索引)。箱子的数量永远不会精确地表示到网格中。如何确保将所有随机值分配给二维网格上的唯一索引?
def chests():
global chest
chest = int(input("How many chests would you like in the game?"))
for i in range(0,chest):
board[randint(0, 4)][randint(0, 4)] = "T"
return board
最佳答案
在我看来,你需要生成所有可能的指数,然后随机选择一个“总体”:
import itertools
import random
chest_count = 8
BOARD_SIZE = 4
indices = list(itertools.product(range(BOARD_SIZE), repeat=2))
chest_locations = random.sample(indices, chest_count)
for i, j in chest_locations:
board[i][j] = 'T'
结果是
O(BOARD_SIZE^2)
。有更复杂的方法——例如,不需要生成整个电路板的索引,您可以对一个扁平电路板的总体进行采样,然后在此之后生成索引:locations = random.sample(range(BOARD_SIZE * BOARD_SIZE), chest_count) # xrange on python2.x
for location in locations:
j, i = divmod(location, BOARD_SIZE)
board[i][j] = 'T'
最终结果是
O(chest_count)
它可能比董事会的规模小得多——然而,我怀疑你的董事会是否真的足够大以至于重要。关于python - 在Python列表中生成不会在同一索引中重复的随机值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40873154/