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

新手上路,请多包涵

我尝试了几种方法,但似乎都不适合我。

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

if not 0 in board:
     # the board is "full"

然后我尝试:

 if not 0 in board[0] or not 0 in board[1]:
    # the board is "full"

这些方法都不起作用,尽管第二种方法通常会让数组填满更多。 (我写了代码来随机填充数组)。

原文由 CtrlAltF2 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 781
2 个回答

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

 if not any(0 in x for x in board):
    pass  # the board is full

每当遇到带有 0 的元素时,使用 any() 将作为一个短暂停留,因此您无需迭代其余部分。

原文由 zwer 发布,翻译遵循 CC BY-SA 4.0 许可协议

我会尝试解决你做错了什么:

if not 0 in board[0] or not 0 in board[1]: 这几乎是正确的 - 但你应该使用 and 因为要被认为是满的,两个板不能同时有 0。

一些选项:

 if not 0 in board[0] and not 0 in board[1]: # would work

if 0 not in board[0] and 0 not in board[1]: # more idiomatic

if not(0 in board[0] or 0 in board[1]): # put "not" in evidence, reverse logic

if not any(0 in b for b in board): # any number of boards

原文由 nosklo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题