LMc*_*LMc 4 python recursion functional-programming
说我有一个清单:
>>> nested=[[1, 2], [3, [4]]]
Run Code Online (Sandbox Code Playgroud)
我试图得到一个函数,[1,1,0]如果我正在寻找将返回4。如果指定的元素不在列表中,则它将返回一个空列表[]。
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
Run Code Online (Sandbox Code Playgroud)
函数调用看起来像这样:
>>> locate(nested,4)
[1,1,0]
Run Code Online (Sandbox Code Playgroud)
递归函数可能不是最佳解决方案,而只是我的尝试。
您可能考虑改用某种树数据结构,但这是当前数据结构的一个示例:
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
Run Code Online (Sandbox Code Playgroud)