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

2024-04-25 04:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个扫雷游戏随机生成炸弹。但有时我发现在我的炸弹坐标表上有重复的东西。如何检查列表中的重复项并用其他随机坐标替换它们。你知道吗

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)

用户可以通过输入GRID_TILES来决定电路板有多大。 如果他们输入5,电路板将是5x5。炸弹的数量是:

GRID_TILES * GRIDTILES / 5

Tags: fromimport游戏列表defcreaterandomnum
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]

每次搜索整个炸弹列表都要花费O(n)(线性时间)。为什么不改用set?一个集合保证您将得到不同的(散列)元素。你知道吗

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)

让我举一个集合的例子:

>>> 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 randint

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

如果新生成的点已经在列表中,那么i不会递增,我们将找到另一个新生成的点,直到它不在BOMBS中。你知道吗

希望有帮助!!你知道吗

相关问题 更多 >