gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:07:56 25 4
gpt4 key购买 nike

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

    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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com