代码之家  ›  专栏  ›  技术社区  ›  CtrlAltF2 BoldX

Python——我如何才能找到一个多维数组中存在的项?

  •  0
  • CtrlAltF2 BoldX  · 技术社区  · 6 年前

    我试过几种方法,但都不管用。

    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"
    

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

    4 回复  |  直到 6 年前
        1
  •  1
  •   zwer    6 年前

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

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

    使用 any() 当遇到具有 0 这样你就不需要重复其他的部分了。

        2
  •  2
  •   nosklo    6 年前

    我会努力解决你做错了什么:

    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
  •  0
  •   Andrej Kesely    6 年前

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

    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
    
        4
  •  0
  •   piman314    6 年前

    如果可以使用标准库以外的工具 numpy 是长时间使用多维数组的最佳方法。

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

    输出:

    True