我有一个网格(6行,5列):
grid = [
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
]
Run Code Online (Sandbox Code Playgroud)
我增加了网格,它可能变成如下:
grid = [
[{"some" : "thing"}, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, {"something" : "else"}, None],
[None, {"another" : "thing"}, None, None, None],
[None, None, None, None, None],
]
Run Code Online (Sandbox Code Playgroud)
我想删除包含所有内容 None的整个行和列.所以在前面的代码中,网格将转换为:
grid = [
[{"some" : "thing"}, None, None],
[None, None, {"something" : "else"}],
[None, {"another" : "thing"}, None],
]
Run Code Online (Sandbox Code Playgroud)
我删除了第1,2,5行(零索引)和第2列和第4列.
我现在删除行的方式:
for row in range(6):
if grid[row] == [None, None, None, None, None]:
del grid[row]
Run Code Online (Sandbox Code Playgroud)
我还没有一个像样的删除None列的方法.这样做有"pythonic"方式吗?
这不是最快的方式,但我认为这很容易理解:
def transpose(grid):
return zip(*grid)
def removeBlankRows(grid):
return [list(row) for row in grid if any(row)]
print removeBlankRows(transpose(removeBlankRows(transpose(grid))))
Run Code Online (Sandbox Code Playgroud)
输出:
[[{'some': 'thing'}, None, None],
[None, None, {'something': 'else'}],
[None, {'another': 'thing'}, None]]
Run Code Online (Sandbox Code Playgroud)
它是如何工作的:我zip用来编写一个转换行和列的函数.第二个函数removeBlankRows删除所有元素都为None的行(或在布尔上下文中计算为false的任何行).然后执行整个操作我转置网格,删除空白行(这是原始数据中的列),再次转置,然后删除空行.
如果仅删除None而不是其他评估为false的内容很重要,请将removeBlankRows函数更改为:
def removeBlankRows(grid):
return [list(row) for row in grid if any(x is not None for x in row)]
Run Code Online (Sandbox Code Playgroud)