I have a grid (6 rows, 5 columns):
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],
]
I augment the grid and it might turn into something like:
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],
]
I want to remove entire rows and columns that have all Nones in them. So in the previous code, grid would be transformed into:
grid = [
[{"some" : "thing"}, None, None],
[None, None, {"something" : "else"}],
[None, {"another" : "thing"}, None],
]
I removed row 1, 2, 5 (zero indexed) and column 2 and 4.
The way I am deleting the rows now:
for row in range(6):
if grid[row] == [None, None, None, None, None]:
del grid[row]
I don’t have a decent way of deleting None columns yet. Is there a “pythonic” way of doing this?
It’s not the fastest way but I think it’s quite easy to understand:
Output:
How it works: I use
zipto write a function that transposes the rows and columns. A second functionremoveBlankRowsremoves rows where all elements are None (or anything that evaluates to false in a boolean context). Then to perform the entire operation I transpose the grid, remove blank rows (which are the columns in the original data), transpose again, then remove blank rows.If it’s important to only strip None and not other things that evaluate to false, change the removeBlankRows function to: