[英]Python 2D List issue
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:然后定义一个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 :现在我想要这个 function 返回一个布尔值,如果给定的(行,列) position 为“无”,则返回True ,否则返回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.我遇到的麻烦是我不知道如何比较列表的(行,列)信息然后output bool值。
Try using tuple[int, ...]
for your type hint for position:尝试使用
tuple[int, ...]
作为 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: Output:
False
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.