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

Python井字棋AI开发:优化actions函数的Pythonic实现咨询

Optimizing the actions Function for Your Tic-Tac-Toe AI

Hey Matthew, nice work getting your Tic-Tac-Toe AI off the ground! Let's refine that actions function to be more concise and Pythonic—here are a couple of clean, readable approaches:

1. Set Comprehension (The Most Pythonic Pick)

This is the go-to pattern for creating sets in Python when you can define your logic in a single, declarative expression. It cuts out all the boilerplate of initializing an empty set and manually adding items:

def actions(board):
    """Returns set of all possible actions (i, j) available on the board."""
    return {(i, j) for i, row in enumerate(board) for j, cell in enumerate(row) if cell is EMPTY}

Why this works better:

  • It directly states your intent: "collect all (i,j) pairs where the cell is empty" instead of walking through step-by-step commands
  • Uses cell is EMPTY instead of cell is None—since you’ve already defined EMPTY = None, this makes the code more maintainable (if you ever redefine EMPTY, you won’t have to update this check)
  • Keeps the function short and focused, which aligns with Python’s "readability counts" philosophy

2. Generator Expression Wrapped in set()

If you prefer a slightly more explicit (but still concise) style, you can use a generator expression inside the set() constructor:

def actions(board):
    """Returns set of all possible actions (i, j) available on the board."""
    return set((i, j) for i, row in enumerate(board) for j, cell in enumerate(row) if cell is EMPTY)

This behaves exactly like the set comprehension, but some developers find it more intuitive if they’re already used to generator expressions for other iterables.

Bonus: Line-Breaked Format for Clarity

If you want to make the logic even easier to scan (especially useful if you add more conditions later), split the comprehension across lines:

def actions(board):
    """Returns set of all possible actions (i, j) available on the board."""
    return {
        (i, j) 
        for i, row in enumerate(board) 
        for j, cell in enumerate(row) 
        if cell is EMPTY
    }

All these versions maintain the exact same functionality as your original code, but they’re cleaner, shorter, and feel more idiomatic to Python.

内容的提问来源于stack exchange,提问作者Matthew Poell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:32:28