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

如何用单下标访问Python嵌套列表元素并实现put_piece函数

关于使用replace_elem实现put_piece函数的疑问

现有replace_elem函数

这个函数用于创建并返回一个新列表,仅替换指定下标位置的元素:

def replace_elem(lst, index, elem):
    """Create and return a new list whose elements are the same as those in LST except at index INDEX, which should contain element ELEM instead.
    >>> old = [1, 2, 3, 4, 5, 6, 7]
    >>> new = replace_elem(old, 2, 8)
    >>> new
    [1, 2, 8, 4, 5, 6, 7]
    >>> new is old # check that replace_elem outputs a new list
    False
    """
    assert index >= 0 and index < len(lst), 'Index is out of bounds'
    return [elem if i == lst[index] else i for i in lst]

需要实现的put_piece函数

目标是在棋盘的指定列中放入玩家的棋子(放到该列最底部的空位),返回棋子所在行下标(列满则返回-1)和新棋盘:

def put_piece(board, max_rows, column, player):
    """Puts PLAYER's piece in the bottommost empty spot in the given column of the board.
    Returns a tuple of two elements:
    1. The index of the row the piece ends up in, or -1 if the column is full.
    2. The new board
    >>> rows, columns = 2, 2
    >>> board = create_board(rows, columns)
    >>> row, new_board = put_piece(board, rows, 0, 'X')
    >>> row
    1
    >>> row, new_board = put_piece(new_board, rows, 0, 'O')
    >>> row
    0
    >>> row, new_board = put_piece(new_board, rows, 0, 'X')
    >>> row
    -1
    """

我的疑问

提示称需两次使用replace_elem函数,但该函数仅接受单个下标参数指定替换位置。我想了解:

  • 如何用单下标表示类似第一行第三列这样的二维位置?
  • 如何确保最终返回的是完整的棋盘,而不是仅修改后的某一行数据?

注:此内容为自学所用,并非作业。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:17:29