如何优化二维数组特定值计数的双层循环?以棋盘空白格统计为例
Great question! Let's break down how we can simplify and optimize your blank space counting task—while keeping things efficient.
First, a quick reality check: since we have to check every cell to count blank spaces, we can't escape an O(width*height) time complexity. But we can make the code cleaner and faster by leveraging Python's built-in tools, which are implemented in optimized C under the hood.
Here are a few better approaches:
1. Use sum() with row-wise count()
This is the most straightforward and readable method. We count the number of 0s in each row, then sum those counts:
blank_spaces = sum(row.count(0) for row in game.__board_state__)
The row.count(0) method is optimized, and using a generator expression with sum() avoids creating unnecessary intermediate lists, keeping memory usage low.
2. Flatten the board with itertools.chain
If you prefer working with a flattened version of the board, itertools.chain can turn your 2D list into a single iterable of cells. Then you can either count directly or use a memory-efficient generator with sum():
from itertools import chain # Option 1: Flatten to a list and count (uses more memory) blank_spaces = list(chain.from_iterable(game.__board_state__)).count(0) # Option 2: Generator expression (memory-light) blank_spaces = sum(1 for cell in chain.from_iterable(game.__board_state__) if cell == 0)
3. Pre-maintain a counter (for frequent queries)
If you need to count blank spaces very often (like in every game loop iteration), the ultimate optimization is to track the count dynamically instead of recalculating it every time:
- When initializing the game:
self.blank_spaces = self.width * self.height - When placing a non-zero piece on the board:
self.blank_spaces -= 1 - When resetting a cell back to 0:
self.blank_spaces += 1
Now you can get the blank space count in O(1) time just by accessing game.blank_spaces—no loops needed at all!
All these approaches are better than hand-writing nested for loops, as they're either more readable, faster, or both.
内容的提问来源于stack exchange,提问作者Suhail Gupta

