在Python列表中生成不在同一索引中重复的随机值

use*_*028 2 python arrays grid list multidimensional-array

我正在制作一个程序,我需要在列表中生成随机值.要求用户输入他们想要在2D网格上生成多少随机值(箱子 - 由字母'T'表示).问题是,当用户输入"8"作为他们想要生成的随机"箱子"的数量时,有时只会为网格生成5或6个箱子(可能是因为随机整数重复到网格上而不是网格中唯一点的索引).箱子的数量永远不会准确地表示给网格.如何确保将所有随机值分配给2D网格上的唯一索引?

    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
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 6

在我看来,你需要生成所有可能的索引,然后随机选择一个"人口":

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'
Run Code Online (Sandbox Code Playgroud)

这最终成为了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'
Run Code Online (Sandbox Code Playgroud)

这最终O(chest_count)会比电路板尺寸小得多 - 但是,我怀疑你的电路板实际上是否足够重要:-).