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

Time:10-27

The print method should read: "From square 'x', 'y' we find 'animal'". I must use enumerate -method to get the coordinates of the letters that represent animals and I'm struggling. The check-field method should call check_square method on every iteration.

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)

CodePudding user response:

Change your check_field function to:

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

The way yours is written, i and j are tuples. You are incorrectly iterating over i in the second for loop. You are also passing enumerate objects to check_square when you should be passing the indices/coordinates themselves.

You'll also want to edit your check_square function, specifically the string-formatting:

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

Should become:

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

Your ANIMALS dictionary doesn't have a key-value pair for " ". Trying to access that key will raise a KeyError. Using the .get method allows you to provide a default in case a key is not present. Alternatively, you could also just have added an entry for " " in ANIMALS.

  • Related