【问题标题】:Python - How can I find if an item exists in multidimensional array?Python - 如何查找一个项目是否存在于多维数组中?
【发布时间】:2018-12-24 11:12:50
【问题描述】:

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

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"

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

【问题讨论】:

  • 你所说的“没有工作”到底是什么意思?
  • # the board is full (因为没有更好的词)在错误的时间运行。

标签: python arrays python-3.x list


【解决方案1】:

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

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

当遇到包含0 的元素时,使用any() 将作为一个临时停止,因此您无需遍历其余部分。

【讨论】:

  • 为什么要使用1 并在生成器表达式中添加条件?只需将条件作为值:any(0 in x for x in board)
【解决方案2】:

我会尝试解决你做错的事情:

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

【讨论】:

    【解决方案3】:

    如果您可以使用标准库之外的工具numpy 是长期使用多维数组的最佳方式。

    board = [[0,0,0,0],[0,0,0,0]]
    board = np.array(board)
    print(0 in board)
    

    输出:

    True
    

    【讨论】:

    • 我希望我的程序尽可能地轻量级。与其他人提出的其他一些单行相比,使用 numpy 是否有任何 主要 优势?
    • 这真的取决于你正在使用什么操作,但我想说一般来说,与在 python 中使用循环相比,numpy 会加快速度。此外,索引的语法非常灵活,即返回i'th 行将是board[:, i]
    【解决方案4】:

    itertools 再次尝试chain(这样它可以处理多行):

    from itertools import chain
    
    board = [[0,0,0,0],[0,0,0,0]]
    
    def find_in_2d_array(arr, value):
        return value in chain.from_iterable(arr)
    
    print(find_in_2d_array(board, 0))
    print(find_in_2d_array(board, 1))
    

    打印:

    True
    False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 2011-02-14
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多