【问题标题】:How to iterate through a sub section of a 2d list?如何遍历二维列表的子部分?
【发布时间】:2020-05-23 03:34:30
【问题描述】:

我正在为 connect4 制作一个更新板,并尝试在板上的前一个上堆叠一个。但是遍历董事会让我感到困惑。我知道 for 循环不正确,因为它只是一个数字。但是我将如何做到这一点(playcol 是恒定的,它将是 3)。除了可能使用切片之外,在 google 上找不到很多东西吗?

'''

   board = [[0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0],
         [0,0,0,1,0,0,0]]
   def updateboard(playcol,board):
       x=0
       for x in board[x][playcol]:
           if board[x][playcol] == 0:
               try:
                   continue
               #if it goes too far past it will throw index error and return the previous
               except IndexError:
                   board[x-1][playcol] = 1
           #else there is a number already there and make the one before it a number
           elif board[x][playcol] != 0:
               board[x-1][playcol] = 1
       print(board)

'''

【问题讨论】:

    标签: python-3.x loops iteration


    【解决方案1】:

    不确定您到底要做什么,使用 numpy 很可能有更有效的方法来做到这一点。但是,由于这是一个简单的函数,而您只是使用列表列表,我认为会为此实现一个解决方案。

    我不会使用 try 和 excepts,而是循环遍历板的长度。我不确定你想在你的板上进行什么样的错误处理,但我只是把它打印出来,你不能玩。

    见下文。

    board = [[0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0],
         [0,0,0,1,0,0,0]]
    def updateboard(playcol,board):
        for i in range(len(board)):
            if board[i][playcol]==1:
                if (i-1) >=0:
                    board[i-1][playcol]=1
                else:
                    print("cannot play that column")
            elif i==len(board) and board[i][playcol]==0:
                board[i][playcol]=1
        print(board)
    updateboard(3,board)
    
    [[0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0], 
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 0, 0], 
    [0, 0, 0, 1, 0, 0, 0]]
    
    

    【讨论】:

    • 谢谢,这确实是我想要的。不认为如果它是 2d 你可以做 len(board) 但猜它是有道理的。我也尝试使用 try 并且没有特别的原因,如果这令人困惑,很抱歉。
    猜你喜欢
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 2014-06-11
    • 1970-01-01
    • 2014-02-14
    • 2016-11-04
    相关资源
    最近更新 更多