Python - 如何查找多维数组中是否存在项目?

DRO*_*mes 4 python arrays list python-3.x

我尝试了几种方法,但似乎没有一种对我有用。

board = [[0,0,0,0],[0,0,0,0]]

if not 0 in board:
     # the board is "full"
Run Code Online (Sandbox Code Playgroud)

然后我尝试:

if not 0 in board[0] or not 0 in board[1]:
    # the board is "full"
Run Code Online (Sandbox Code Playgroud)

这些方法都没有奏效,尽管第二种方法通常会让数组填满更多。(我编写了代码来随机填充数组)。

zwe*_*wer 5

您需要遍历列表的所有索引以查看元素是否是嵌套列表之一中的值。您可以简单地遍历内部列表并检查元素是否存在,例如:

if not any(0 in x for x in board):
    pass  # the board is full
Run Code Online (Sandbox Code Playgroud)

any()每当遇到带有 a 的元素时,Using都将作为一个短暂停留0,因此您无需遍历其余元素。