将网格划分为可管理的列表

时间:2018-08-19 21:16:11

标签: python list

我正在尝试如下分割网格:

grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]

我理想中想要的是一种可以轻松访问每个元素的格式。我一直在玩split的组合,但是到目前为止它还没有用。有什么建议么?谢谢。

3 个答案:

答案 0 :(得分:2)

您已经可以使用2个索引轻松访问网格的任何元素。

grid[0][0]

例如将成为第一行的第一个元素。

答案 1 :(得分:1)

一种可能性是使用键为元组的字典。这将允许您使用grid[row, column]访问其元素。这是创建和初始化它的一种方法:

data = """\
    ......
    .OO...
    OOOO..
    OOOOO.
    .OOOOO
    OOOOO.
    OOOO..
    .OO...
    ......
"""

# Create dictionary from data list.
grid = {}
for i, row in enumerate(line.strip() for line in data.splitlines()):
    for j, elem in enumerate(row):
        grid[i, j] = elem

print('Access each element of the grid:')
for i in range(8):
    for j in range(6):
        print('grid[{}, {}] = {!r}  '.format(i, j, grid[i, j]), end='')
    print()

输出:

Access to each element of grid:
grid[0, 0] = '.'  grid[0, 1] = '.'  grid[0, 2] = '.'  grid[0, 3] = '.'  grid[0, 4] = '.'  grid[0, 5] = '.'  
grid[1, 0] = '.'  grid[1, 1] = 'O'  grid[1, 2] = 'O'  grid[1, 3] = '.'  grid[1, 4] = '.'  grid[1, 5] = '.'  
grid[2, 0] = 'O'  grid[2, 1] = 'O'  grid[2, 2] = 'O'  grid[2, 3] = 'O'  grid[2, 4] = '.'  grid[2, 5] = '.'  
grid[3, 0] = 'O'  grid[3, 1] = 'O'  grid[3, 2] = 'O'  grid[3, 3] = 'O'  grid[3, 4] = 'O'  grid[3, 5] = '.'  
grid[4, 0] = '.'  grid[4, 1] = 'O'  grid[4, 2] = 'O'  grid[4, 3] = 'O'  grid[4, 4] = 'O'  grid[4, 5] = 'O'  
grid[5, 0] = 'O'  grid[5, 1] = 'O'  grid[5, 2] = 'O'  grid[5, 3] = 'O'  grid[5, 4] = 'O'  grid[5, 5] = '.'  
grid[6, 0] = 'O'  grid[6, 1] = 'O'  grid[6, 2] = 'O'  grid[6, 3] = 'O'  grid[6, 4] = '.'  grid[6, 5] = '.'  
grid[7, 0] = '.'  grid[7, 1] = 'O'  grid[7, 2] = 'O'  grid[7, 3] = '.'  grid[7, 4] = '.'  grid[7, 5] = '.'  

答案 2 :(得分:0)

这是有效的最终代码:

grid = input("Enter list elements separated by comma ")
n_row,n_col = len(grid),len(grid[0])
for i in range(0,n_col):
    for j in range(0,n_row):
        print(grid[j][i],end='')
    print('\n')