[英]In Python, how do you return a list of indexes for an arbitarily nested element?
[英]Python: How to find certain characters in nested list and return indexes
我正在尋找一種方法來返回這些特定字符所在位置的索引元組列表。
例如,我想知道在我的嵌套列表中哪里有空格(“”)。
說我有這個:
board = [
["a", " ", " "],
[" ", "x", " "],
[" ", "b", " "]
]
我的 function 將是:
def empty_squares(board):
"""Return a list of the empty squares in the board, each as
a (row, column) tuple"""
因此,如果我運行 function 它將返回[(0,1), (0,2), (1,0), (1,2), (2,0), (2,2)]
。
我只是不確定如何為嵌套列表執行此操作。
謝謝!
您可以遍歷電路板並使用 enumerate 來跟蹤索引。
l = []
for indexa, e in enumerate(board):
for indexb, c in enumerate(e):
if c == ' ':
l.append((indexa, indexb))
或者簡單地使用列表理解:
l = [(indexa, indexb) for indexb, c in enumerate(e) for indexa, e in enumerate(board) if c == ' ']
兩者都會 output:
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 2)]
也許與枚舉?
board = [
["a", " ", " "],
[" ", "x", " "],
[" ", "b", " "]
]
def empty_squares(board, symbol):
"""
Return a list of the empty squares in the board, each as
a (row, column) tuple
"""
empty = []
for row, sublist in enumerate(board):
for column, item in enumerate(sublist):
if item == symbol:
empty.append((row, column))
return empty
>>> empty_squares(board, ' ')
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 2)]
最簡單的方法可能是使用numpy.where()
。
import numpy as np
board = [
["a", " ", " "],
[" ", "x", " "],
[" ", "b", " "]
]
idxs = [(i, j) for i, j in zip(*np.where(np.array(board) == ' '))]
print(idxs)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.