如何用单下标访问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
相关产品推荐
相关产品推荐

