删除网格中的空列

时间:2019-10-01 18:14:13

标签: python grid

import random


def gridfunction(h,i,j):
   grid = [[random.randint(0,(j-1)) for x in range(h)] for y in range(i)]
   for n in grid:
      row = ' '
      for sub in n:
          row += str(sub) + ' '
      print(row)
   return grid


h = int(input('h'))
i = int(input('i'))
j = int(input('j'))

grid = gridfunction(h,i,j)

x,y = map(int, input('x,y').split(','))

def search(grid, x, y):
    coords = grid[x][y]
    grid[x][y] = ' '

    for nextx in range(-1, 2):
        for nexty in range(-1, 2):
            if abs(nextx) + abs(nexty) == 1 and 0 <= x+nextx < len(grid) and 0 <= y+nexty < len(grid[0]) and grid[x+nextx][y+nexty] == coords:
                grid = search(grid, x+nextx, y+nexty)
    return grid

search(grid, x,y)
a = grid
for s in a:
      print(*s)

我一直在尝试(并且失败)在这里添加一个函数来检测网格中何时有空列。我尝试这样做:

grid = gridfunction(h,i,j)
for y in range(i):
  if grid[y] == [[' ']* i]:
    del grid[y]
print(grid)

但是它只是打印出相同的网格。我也尝试过使用zip函数,但由于某种原因,它会发出TypeError:类型为'NoneType'的对象没有len()(只是在堆栈溢出时看到了)

def transpose(grid):
    return zip(*grid)

def removeBlankRows(grid):
    return [list(x) for x in grid if any(x is not ' ' for x in x)]

print(removeBlankRows(transpose(removeBlankRows(transpose(grid)))))

0 个答案:

没有答案