在多维列表中引用项目的正确方法是什么?

我正在尝试编写命令行minesweeper克隆,而我的地雷生成器代码遇到了一些麻烦。


def genWorld(size, mines):

    world = []

    currBlock = []

    for i in range(size):

        for j in range(size):

            currBlock.append("x")

        world.append(currBlock)

        currBlock = []

    for i in range(mines):

        while True:

            row = randint(0, size)

            col = randint(0, size)

            if world[row[col]] != "M":

                break

        world[row[col]] = "M"

    printWorld(world)

运行此命令时,出现错误:


Traceback (most recent call last):

  File "C:\Python33\minesweeper.py", line 28, in <module>

    genWorld(9, 10)

  File "C:\Python33\minesweeper.py", line 23, in genWorld

    if world[row[col]] != "M":

TypeError: 'int' object is not subscriptable

我以为这意味着我以错误的方式引用了列表,但是我将如何正确地做到这一点呢?


慕的地10843
浏览 162回答 3
3回答

Qyouu

您给出row一个整数值。&nbsp;row[col]然后尝试访问该整数的元素,这将导致错误。我想你想要的是world[row][col]。

浮云间

你可能想world[row][col],作为world[row]给出了一个列表,然后[col]选择从该列表中的元素。

饮歌长啸

我会考虑使用字典而不是嵌套数组:# positions for minesmines = set()while len(mines) != mines:&nbsp; &nbsp; pos = (randint(0, size), randint(0, size))&nbsp; &nbsp; if not pos in mines:&nbsp; &nbsp; &nbsp; &nbsp; mines.add(pos)# initialize worldworld = {}for x in range(size):&nbsp; &nbsp; for y in range(size):&nbsp; &nbsp; &nbsp; &nbsp; if (x, y) in mines:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; world[x, y] = 'M'&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; world[x, y] = ' '您还可以使用dict的get()函数,None如果没有我的函数,该函数将返回,但是您也可以继续使用set(if pos in mines: booom())以使事情变得简单。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python