You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数字井字棋开发:如何不修改原列表将零元素打印为空格?

Solution for Displaying Empty Spaces Instead of Zeros in Your Sum-to-15 Tic-Tac-Toe Game

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.board list 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 20:18:12