区域中对象的索引不正确(二维列表)python

问题描述 投票:0回答:1

我已经实现了一个程序,该程序应该依赖于该区域中物体的坐标。该区域形成为二维列表。问题在于,通常输出是正确的,但是,一个对象执行了错误的坐标。首先,第一个函数中的索引存在问题,但后来我将其移至第二个函数(cols.index(value))(cols 是列)。也许这就是原因,或者我可能错误地实施了其他东西?该程序不应该使用 numpy 工具

提前感谢您的帮助!

OBJECTS = {
    "h": "house",
    "s": "shop",
    "g": "gas station",
    "p": "pharmacy",
    "c": "cinema"
}


def check_area(char, row_n, col_n):
    """
    Explore a tile - if there is an animal, prints the
    location and name of the animal
    """
    if char in list(OBJECTS):
        print(f"Tile ({col_n}, {row_n}) disposes a {OBJECTS[char]}")


def check_region(td_list):
    """
    This function explores an entire field by calling the explore_tile
    function for each tile in the field.
    """
    for rows, cols in enumerate(td_list):
        for value in cols:
            if value != " ":
                check_area(value, rows, cols.index(value))


region = [
    [" ", "h", " ", " ", "p"],
    [" ", "s", "g", "s", " "],
    ["c", " ", "h", "s", " "]
]
check_region(region)

输出:

Tile (1, 0) 处置房屋 瓷砖 (4, 0) 处置药房 瓦片(1, 1)配置店铺 方块 (2, 1) 布置一个加油站 Tile (1, 1) 配置商店 Tile (0, 2) 配置电影院 瓷砖 (2, 2) 处置房屋 瓷砖 (3, 2) 配置商店

list function for-loop
1个回答
0
投票

您的问题出在这一行:

check_area(value, rows, cols.index(value))

当一行中有两个相同的值时(例如第 1 行中的

s
),
cols.index
返回第一个匹配值的索引。这样你就得到了

Tile (1, 1) disposes a shop
Tile (2, 1) disposes a gas station
Tile (1, 1) disposes a shop

而不是

Tile (1, 1) disposes a shop
Tile (2, 1) disposes a gas station
Tile (3, 1) disposes a shop

只需枚举列值而不是使用

cols.index
:

即可轻松解决此问题
def check_region(td_list):
    """
    This function explores an entire field by calling the explore_tile
    function for each tile in the field.
    """
    for row, cols in enumerate(td_list):
        for col, value in enumerate(cols):
            if value != " ":
                check_area(value, row, col)

输出:

Tile (1, 0) disposes a house
Tile (4, 0) disposes a pharmacy
Tile (1, 1) disposes a shop
Tile (2, 1) disposes a gas station
Tile (3, 1) disposes a shop
Tile (0, 2) disposes a cinema
Tile (2, 2) disposes a house
Tile (3, 2) disposes a shop
© www.soinside.com 2019 - 2024. All rights reserved.