![](/img/trans.png)
[英]Python - Is there a way to get (str, index) instead of (index, str) using enumerate?
[英]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.