我将如何迭代将数组输入转换为整数

时间:2019-04-14 10:29:39

标签: python multidimensional-array

假设我将以下输入作为多维列表

chain = [['.','.','.','.','.','.','.']
        ['.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.']]

我如何遍历循环并计算每个项目。

2 个答案:

答案 0 :(得分:1)

# your mapping
m = '.C-|'

# iterate rows then inside iterate columns
out = [[m.index(c) for c in r] for r in grid]

答案 1 :(得分:0)

您可以按如下方式使用numpy库:

import numpy as np
grid = np.array([['.','.','.','.','.','.','.'],
        ['.','C','-','C','-','C','.'],
        ['.','.','.','|','.','.','.'],
        ['.','.','.','C','.','.','.'],
        ['.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.'],
        ['.','.','.','.','.','.','.']])

grid = np.where(grid=='.', '0', grid)
grid = np.where(grid=='C', '1', grid)
grid = np.where(grid=='-', '2', grid)
grid = np.where(grid=='|', '3', grid)