简体   繁体   English

使用枚举查找数组中str的索引

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

I am creating a simple game grid. 我正在创建一个简单的游戏网格。 I want to be able to find the location of a player's piece to work out their next move. 我希望能够找到玩家棋子的位置以制定他们的下一步行动。 I have tried using enumerate but it does not find anything and I cannot figure out my error. 我尝试使用枚举,但是找不到任何东西,因此无法弄清我的错误。 Any suggestions would be welcome. 欢迎大家提出意见。

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)

I don't know if enumerate is the right option to use as I need to know just the row, the column is not really necessary. 我不知道枚举是否是正确的选择,因为我只需要知道行,那么列就不是必需的。 Thanks 谢谢

You are looping over just the nested rows; 您仅遍历嵌套的行; you are not looping over the columns. 您没有在列上循环。

Your list structure looks like: 您的列表结构如下所示:

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

but you only loop over the outer list. 但您只能遍历外部列表。 This makes x reference a whole list ; 这使x引用了整个列表 'P1' is never going to be equal to ['_', 'P1', 'P2', 'P3', 'P4'] . 'P1'永远不会等于['_', 'P1', 'P2', 'P3', 'P4'] You'll have to loop over the inner list too: 您还必须遍历内部列表:

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