数字井字棋开发:如何不修改原列表将零元素打印为空格?
I’ve got a clean, concise fix that avoids nested loops, keeps your code under line-length limits, and leaves your original self.board data untouched. Here’s how to implement it:
Core Approach
We’ll use a tiny helper function to handle converting zeros to spaces, then use map() to apply this logic to every element in a row in one go. This eliminates repeated ternary operators and keeps your formatting code tight and readable.
Updated Code
print(" 0 1 2 ") # Helper function to convert 0 to space, else return the number as a string def display_val(val): return ' ' if val == 0 else str(val) for row in range(self.size): # Process all three columns in the current row with our helper col0, col1, col2 = map(display_val, self.board[row]) # Use f-strings for cleaner, more readable formatting print(f" {row} {col0} | {col1} | {col2} ") if row < 2: print(' -----------')
Why This Works
- No original data modification: The helper function only transforms values for display—your
self.boardlist stays intact with zeros preserved for game logic. - No nested loops:
map()handles iterating over the row’s elements for you, so you don’t add unnecessary complexity or runtime overhead. - Line-length compliant: By extracting the conversion logic to a helper function, your formatting line stays short and follows style guidelines.
- Maintainable: The helper function makes it immediately clear what’s happening with zero values, which is easier to update later than inline ternary operators.
Alternative (One-Liner Conversion, No Helper Function)
If you prefer extra brevity (though slightly less readable), you can replace the helper function with a lambda inside map():
print(" 0 1 2 ") for row in range(self.size): col0, col1, col2 = map(lambda v: ' ' if v == 0 else str(v), self.board[row]) print(f" {row} {col0} | {col1} | {col2} ") if row < 2: print(' -----------')
Either approach will give you the clean, space-filled board you want without sacrificing code quality or performance.
内容的提问来源于stack exchange,提问作者Saqlain Sajid

