如何检查嵌套列表中的所有方块并打印它们的索引(如坐标)?

How is it possible check all the squares from nested list and print their indexes like coordinates?

打印方法应为:“从正方形 'x'、'y' 我们找到 'animal'”。我必须使用 enumerate -method 来获取代表动物的字母的坐标,我正在努力。检查字段方法应在每次迭代时调用 check_square 方法。

ANIMALS = {
    "a": "alpaca",
    "k": "kangaroo",
    "@": "cat",
    "h": "hamster",
    "l": "leopard"
}


def check_square(char, row_num, col_num):

    if char != " ":    
        print("From square ({}, {}) we find {}"
        .format(col_num, row_num, ANIMALS[char]))



def check_field(field):

    for i in enumerate(field):
        #print(i)
        for j in enumerate(i):
            #print(i)
            #print(enumerate(field))
            #print(i)
            #print(j)
            check_square(field[i], enumerate(j), enumerate(i))


field = [
    [" ", "a", " ", " ", "l"],
    [" ", "k", "@", "k", " "],
    ["h", " ", "a", "k", " "]
]

check_field(field)

将您的 check_field 函数更改为:

def check_field(field):
    for y, row in enumerate(field):
        for x, char in enumerate(row):
            check_square(char, y, x)

按照你的写法,ij 是元组。您在第二个 for 循环中错误地迭代了 i 。当您应该传递 indices/coordinates 本身时,您还将枚举对象传递给 check_square

您还需要编辑 check_square 函数,特别是字符串格式:

.format(col_num, row_num, ANIMALS[char])

应该变成:

.format(col_num, row_num, ANIMALS.get(char, "nothing"))

您的 ANIMALS 词典没有 " " 的键值对。尝试访问该密钥将引发 KeyError。使用 .get 方法允许您提供默认值以防键不存在。或者,您也可以在 ANIMALS.

中添加 " " 的条目