Home > Back-end >  Python 2D List issue
Python 2D List issue

Time:08-10

now I have a list like this:

list1 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 1, 2, 3],
[4, 5, 6, None]
]

And then define a function:

def thefunction(position: tuple[int, int], board: Board) -> bool:
   

Now I want this function return a bool value, returns True if the given (row, column) position is "None", otherwise, return False:

thefunction((0,0), list1)
False

thefunction((3,3), list1)
True

The trouble I encounter is that I don't know how to do the comparison of the (row, column) information of the list and then output bool value.

CodePudding user response:

Try using tuple[int, ...] for your type hint for position:

from typing import Optional


def is_none(position: tuple[int, ...], board: list[list[Optional[int]]]) -> bool:
    if not len(board) or not all(len(row) == len(board) for row in board):
        raise ValueError('Invalid board, must be square.')
    board_rows, board_cols = len(board), len(board[0])
    if len(position) != 2:
        raise ValueError('Position must have exactly two values.')
    row, col = position
    if 0 <= row < board_rows and 0 <= col < board_cols:
        return board[row][col] is None
    raise ValueError('Position must be on board.')


def main() -> None:
    board = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 1, 2, 3],
        [4, 5, 6, None],
    ]
    print(is_none((0, 0), board))
    print(is_none((3, 3), board))


if __name__ == '__main__':
    main()

Output:

False
True
  • Related