在Python列表中生成不在同一索引中重复的随机值
问题描述:
我正在制作一个程序,我需要将随机值生成列表。要求用户输入他们想要在二维网格上产生多少个随机值(箱子 - 由字母'T'表示)。问题是,当用户输入'8'作为他们想要产生的随机“箱子”的数量时,有时只有5或6个箱子产生到网格中(可能是因为随机整数重复到网格上,而不是在网格中的唯一点处的索引)。箱子的数量永远不会准确地表示给电网。我如何确保将所有随机值分配给2D网格上的唯一索引?在Python列表中生成不在同一索引中重复的随机值
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)
这可能是比电路板尺寸更小 - 不过,我怀疑你的董事会实际上是否足够重要:-)。
你可以使用'numpy'还是需要纯粹的python实现? – roganjosh
纯Python实现。 – user3608028