假设我有一个列表:
>>> nested=[[1, 2], [3, [4]]]
如果我正在寻找 4
,我正在尝试获取一个返回 [1,1,0]
的函数。如果指定的元素不在列表中,那么它将返回一个空列表,[]
。
Nested
可以有任何结构,所以我认为某种类型的递归函数最好,但我无法控制结构的深度和广度。
这不是工作代码,但符合我的想法:
def locate(x,element,loc=[0],counter=0):
for c,i in enumerate(x):
if isinstance(i,list):
locate(i,loc+[0],counter+1)
else:
loc[counter]=c
if i==element: return loc
函数调用看起来像这样:
>>> locate(nested,4)
[1,1,0]
递归函数可能不是最好的解决方案,但只是我的尝试。
最佳答案
您可能会考虑改用某种树数据结构,但这是您当前数据结构的示例:
from collections import Iterable
def flatten(collection, depth=()):
for i, element in enumerate(collection):
if isinstance(element, Iterable) and not isinstance(element, str):
yield from flatten(element, depth=depth + (i,))
else:
yield element, depth + (i,)
def locate(nested, element):
for v, indices in flatten(nested):
if v == element:
return indices
关于python - 在 Python 中,如何返回任意嵌套元素的索引列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40164116/