如果在给定的嵌套列表中找到给定的'to_find',我如何编写一个返回true的递归函数。
例如:
>>> searchNested([1,[4, 5, 6, [2, 10], 9], [1, 4, 5]], 2)
True
答案 0 :(得分:3)
def searchNested(xs, y):
if y == xs:
return True
return isinstance(xs, list) and any(searchNested(x, y) for x in xs)
>>> searchNested([1,[4, 5, 6, [2, 10], 9], [1, 4, 5]], 2)
True
>>> searchNested([1,[4, 5, 6, [8, 10], 9], [1, 4, 5]], 2)
False
答案 1 :(得分:0)
先展平,然后使用in
def searchNested(lst,needle):
def flatten(target):
return_list = list()
for element in target:
if isinstance(element,list):
return_list.extend(flatten(element))
else:
return_list.append(element)
return return_list
lst = flatten(lst)
if needle in lst: return True
else: return False