簡體   English   中英

使用枚舉查找數組中str的索引

[英]Using enumerate to find the index of a str in my array

我正在創建一個簡單的游戲網格。 我希望能夠找到玩家棋子的位置以制定他們的下一步行動。 我嘗試使用枚舉,但是找不到任何東西,因此無法弄清我的錯誤。 歡迎大家提出意見。

def createBoard():
    startBoard=[]
    for x in range(0,12):
        startBoard.append(["_"] * 5)
    startBoard[11][1]= 'P1'
    startBoard[11][2]= 'P2'
    startBoard[11][3]= 'P3'
    startBoard[11][4]= 'P4'
    return startBoard

def print_board(board):
        for row in board:
            print (" ".join(row))
        return True


def findBoardLocation(board,a):
    for i in [i for i,x in enumerate(board) if x == a]:
       print('location of {0} is [{1}]'.format(a,i))

startBoard=createBoard()
print_board(startBoard)
a='P1'
findBoardLocation(startBoard,a)

我不知道枚舉是否是正確的選擇,因為我只需要知道行,那么列就不是必需的。 謝謝

您僅遍歷嵌套的行; 您沒有在列上循環。

您的列表結構如下所示:

[['_', '_', '_', '_', '_'],
 ['_', '_', '_', '_', '_'],
 # ...
]

但您只能遍歷外部列表。 這使x引用了整個列表 'P1'永遠不會等於['_', 'P1', 'P2', 'P3', 'P4'] 您還必須遍歷內部列表:

def findBoardLocation(board, a):
    for rowid, row in enumerate(board):
       for colid, column in enumerate(row):
           if column == a:
               print('location of {0} is [{1}][{2}]'.format(a, rowid, colid))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM