Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在随机生成的列表中检查重复项并替换它们_Python_Python 3.x_Random - Fatal编程技术网

Python 在随机生成的列表中检查重复项并替换它们

Python 在随机生成的列表中检查重复项并替换它们,python,python-3.x,random,Python,Python 3.x,Random,我正在用随机生成的炸弹做一个扫雷游戏。然而,有时我发现在我的炸弹坐标表中有重复的。如何检查列表中的重复项并用其他随机坐标替换它们 from random import randint def create_bombpos(): global BOMBS, NUM_BOMBS, GRID_TILES for i in range(0, NUM_BOMBS): x = randint(1, GRID_TILES) y = randint(1, GRI

我正在用随机生成的炸弹做一个扫雷游戏。然而,有时我发现在我的炸弹坐标表中有重复的。如何检查列表中的重复项并用其他随机坐标替换它们

from random import randint

def create_bombpos():
    global BOMBS, NUM_BOMBS, GRID_TILES
    for i in range(0, NUM_BOMBS):
        x = randint(1, GRID_TILES)
        y = randint(1, GRID_TILES)
        BOMBS.append((x, y))
    print(BOMBS)
用户可以通过输入
网格块
来决定电路板的大小。 如果他们输入5,电路板将为5x5。炸弹的数量是:

GRID_TILES * GRIDTILES / 5
来自随机导入randint
def create_bombpos():
全球炸弹、数量炸弹、栅格瓷砖
i=0

而我每次在你的整个炸弹清单中搜索都会花费你
O(n)
(线性时间)。你为什么不改用a呢?一个集合保证您将得到不同的(在散列方面)元素

from random import randint

def create_bombpos():
BOMBS = set()
i = 0
while i<NUM_BOMBS:
   x = randint(1, GRID_TILES)
   y = randint(1, GRID_TILES)
   if (x,y) not in BOMBS
       BOMBS.add((x, y))
       i = i + 1
print(BOMBS)

我可以多次将同一元素添加到集合中,但只会出现一个实例。

使用python集合进行此操作,它将自动检查重复项,并忽略列表中已存在的每个条目。 我还认为运行时比使用列表和手动检查重复项要好得多


链接:

您也可以使用random.sample来实现此目的:

from random import sample

GRID_TILES = 100
NUM_BOMBS = 5

indexes = sample(range(GRID_TILES * GRID_TILES), NUM_BOMBS)
BOMBS = [(i // GRID_TILES, i % GRID_TILES) for i in indexes]

谢谢,这似乎有帮助!我会尽快接受答案。如果你使用一套,为什么要检查(x,y)是否在炸弹中?好的捕获@maximilianPeters。拷贝n粘贴遗漏。无论如何,他似乎不关心运行时间:)好吧,我想即使是99个炸弹的运行时间也可以忽略不计。这看起来像是它会尝试添加数个炸弹,但如果有任何重复,你最终会得到更少的。最好的解决方案IMHO,甚至可以缩短到一行。不检查位置是否存在,因为sample确保每个位置都是唯一的。
>>> a = set()
>>> a.add((1,2))
>>> a
{(1, 2)}
>>> a.add((1,2))
>>> a.add((1,3))
>>> a.add((1,2))
>>> a
{(1, 2), (1, 3)}
from random import sample

GRID_TILES = 100
NUM_BOMBS = 5

indexes = sample(range(GRID_TILES * GRID_TILES), NUM_BOMBS)
BOMBS = [(i // GRID_TILES, i % GRID_TILES) for i in indexes]