控制台网格无法正确打印

时间:2019-01-05 22:35:34

标签: python

我在python中制作了一个可以打印的网格。 它正确显示一系列或列和行。但是,当我想更改网格中的元素时,似乎将其添加到列表中而不是替换所需的索引。 这是代码:

empty = "X"
wall = "O"

rows = 20
columns = 40
grid = ""

def GetIndexFromPosition(x,y):
    index = 0
    for i in range(0,y):
        index += (columns)
    index += x
    print(index)
    return index


for i in range(0,rows):
    row = ""
    for i in range(0,columns):
        row += empty
    grid += """
""" + row

l = list(grid)

l[GetIndexFromPosition(0,0)] = wall

grid = "".join(l)
print(grid)

网格应保持在40 x 20屏幕上,而不是我更改为21个单位长的行。

2 个答案:

答案 0 :(得分:0)

我怀疑它是在添加一个新元素而不是替换它,并将所有内容移动一个索引。要解决此问题,只需删除元素,然后添加新元素,即del l[GetIndexFromPosition(0,0)]

代码:

empty = "X"
wall = "O"

rows = 20
columns = 40
grid = ""

def GetIndexFromPosition(x,y):
    index = 0
    for i in range(0,y):
        index += (columns)
    index += x
    print(index)
    return index


for i in range(0,rows):
    row = ""
    for i in range(0,columns):
        row += empty
    grid += "\n" + row

l = list(grid)

#new code beneath
del l[GetIndexFromPosition(0,0)]

l[GetIndexFromPosition(0,0)] = wall

grid = "".join(l)

print grid

功能:

使其成为函数:

def replace(list, index, new_val):
    del list[index]
    list[index] = new_val

要在您的情况下使用它:

replace(l, GetIndexFromPosition(0,0), wall)

答案 1 :(得分:0)

您的GetIndexFromPosition函数不计算换行符 您在网格字符串中插入的元素。

纠正了换行符的功能:

def GetIndexFromPosition(x,y):
    index = 1
    for i in range(0,y):
        index += (columns + 1)
    index += x
    print(index)
    return index